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 571e7566..cca26768 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,6 +38,61 @@ 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 speakers**: a public list of which speakers are **supported**, **supported with quirks** or + **unsupported**, with what to look for and what to do, kept in its own repository, + [AriaCast/known-speakers](https://github.com/AriaCast/known-speakers), so that adding a speaker + never rebuilds the app. The app downloads it once a day (Settings โ†’ Known speakers, where it can be + switched off, updated by hand and browsed) and ships no copy, so the list is empty until the first + download. Only a newer, valid list is taken, and what the file may change is limited to five + settings (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), each within fixed limits and written only + by maintainers. 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 + 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. +- **"Does it work?"**: the first time you have cast to a speaker for a minute, AriaCast asks once + whether it works: a dialog if the app is open, a notification with the two answers if not. "It + works" is kept on the phone, and offered for the public list only if the list does not already say the + speaker is supported. "There's a problem" asks whether it plays with something wrong or not at all and + what happens, then opens the pre-filled report with that written in. Nothing is sent unless you open + the report; speakers that a Sendspin server pulls from are not asked about. If casting to a single + speaker fails in that first minute, it asks instead whether to report it, with "doesn't work" + already chosen. + Only speakers are asked about or reported: AriaCast receivers, Snapcast, VBAN and Sendspin are + software on a phone, a computer or a server, so they are left out. A speaker is told apart by its + brand and model, never by the name you gave it: if it does not say its model, the report form + leaves "Speaker" empty for you to fill in. For "it works" no log is copied, since there is nothing + to explain. +- **Look for other devices** (Settings โ†’ Known speakers): a scan of about eight seconds, started by + you, for devices AriaCast cannot play to: UPnP devices that are not renderers, and mDNS services such + as Spotify Connect, Sonos, Amazon, HomeKit, HEOS and Bose SoundTouch. Speakers the app already lists + are left out. Tapping one opens a pre-filled report with what the scan learned (name, maker, model, + service types; addresses shortened), so a speaker the app cannot find can still be added to the list. + Nothing is kept or sent unless you open the report. +- **Report speaker**: long-press a speaker (or use the doctor) to open a pre-filled report on GitHub + with who the speaker is and what is known about it; its log lines are copied to paste in, with + addresses shortened. A bot in the known-speakers repository records it: a speaker already listed has + the report counted (the listed status follows the most reported one, and entries a maintainer + checked never change), a new one is added. The log is never copied into the list, and a person can + send three reports a day. "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. - **Plugin API v2**: plugins describe their UI with `ui.render()`; the v1 view methods diff --git a/README.md b/README.md index 6fdc523f..ed969129 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,12 @@ Colors follow your wallpaper (Material You) on Android 12 and newer. Phones get - **Bridge mode**: forward what this device receives to AirPlay, Cast, DLNA, Snapcast or Sendspin speakers. - **Full-screen receiver** for tablets and TVs: artwork colors, clock, "scan to cast here" QR code, burn-in protection. Works with the Android TV remote. - **Video casting** to Google Cast, DLNA and AirPlay, with subtitles and seeking. +- **Known speakers**: a public list of which speakers are supported, supported with quirks or not + supported, kept in [AriaCast/known-speakers](https://github.com/AriaCast/known-speakers) and + downloaded by the app once a day (Settings โ†’ Known speakers; it can be switched off). The first time + you cast to a speaker for a minute, AriaCast asks whether it works, and you can **report** it, or look + for devices it cannot play to, with a pre-filled report on GitHub. A bot records it: a speaker already + listed has the report counted, a new one is added. Logs stay yours. - **Connection doctor**: checks the path from this device to the speaker step by step and tells you which step is broken. - **Web remote**: control AriaCast from any browser on your network through a private link. - **Quick Settings tiles**, a home-screen **widget**, **NFC tags** that start a cast when tapped, and **automation** intents for Tasker and MacroDroid (opt-in). diff --git a/app/build.gradle.kts b/app/build.gradle.kts index bb18388b..b0447585 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -22,6 +22,9 @@ if (keystorePropertiesFile.exists()) { } android { + testOptions { + unitTests.isIncludeAndroidResources = true + } namespace = "com.aria.ariacast" compileSdk = 36 ndkVersion = "27.1.12297006" @@ -146,6 +149,9 @@ dependencies { implementation(libs.jmdns) testImplementation(libs.junit) + // Starts the real app on the JVM: StartupSmokeTest catches crashes that only show at runtime. + testImplementation("org.robolectric:robolectric:4.18.1") + testImplementation("androidx.test:core-ktx:1.6.1") // Self-signed TLS certificates for the fake Google Cast receiver in CastClientTest. testImplementation(libs.bouncycastle.bcpkix) androidTestImplementation(libs.androidx.junit) diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index ef309462..1e83c388 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -81,6 +81,22 @@ + + + + + + (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 +573,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 +617,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 +659,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") @@ -628,12 +680,76 @@ class AudioCastService : Service() { } } + private suspend fun askAboutSpeakerLater(dest: CastDestination) { + val ledger = FeedbackLedger.of(sharedPreferences) + val key = SpeakerFeedback.key(dest.platform, dest.name) + // Either a minute passes, or the cast fails first: then the question is whether to report it. + val failedEarly = withTimeoutOrNull(SpeakerFeedback.ASK_AFTER_MS) { _state.first { it == CastState.ERROR }; true } == true + if (failedEarly) { + if (SpeakerFeedback.shouldAskAfterFailure(_activeDestinations.value.size, ledger.asked(key), dest.platform)) { + ledger.markAsked(key, System.currentTimeMillis()) + askAboutSpeaker(dest, failed = true) + } + return + } + val stillInCast = _activeDestinations.value.any { destKey(it) == destKey(dest) } + if (!SpeakerFeedback.shouldAsk(_state.value == CastState.CASTING, stillInCast, ledger.asked(key), dest.platform)) return + ledger.markAsked(key, System.currentTimeMillis()) + askAboutSpeaker(dest) + } + + /** A dialog if the app is on screen, a notification with the two answers if not. */ + private fun askAboutSpeaker(dest: CastDestination, failed: Boolean = false) { + val castState = listOfNotNull(_state.value.name, _lastError.value?.let { "last error: $it" }).joinToString(", ") + fun open(answer: String? = null) = Intent(this, SpeakerFeedbackActivity::class.java) + .putExtra(SpeakerFeedbackActivity.EXTRA_CAST_STATE, castState) + .putExtra(SpeakerFeedbackActivity.EXTRA_PLATFORM, dest.platform) + .putExtra(SpeakerFeedbackActivity.EXTRA_NAME, dest.name) + .putExtra(SpeakerFeedbackActivity.EXTRA_HOST, dest.host) + .putExtra(SpeakerFeedbackActivity.EXTRA_EXTRA, dest.extra) + .apply { answer?.let { putExtra(SpeakerFeedbackActivity.EXTRA_ANSWER, it) } } + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + if (AppVisibility.visible) { + startActivity(open(if (failed) SpeakerFeedbackActivity.ANSWER_FAILED else null)) + return + } + fun pending(code: Int, answer: String?) = + PendingIntent.getActivity(this, code, open(answer), PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) + val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager + manager.createNotificationChannel(NotificationChannel(FEEDBACK_CHANNEL_ID, getString(R.string.feedback_channel), NotificationManager.IMPORTANCE_LOW)) + manager.notify( + SpeakerFeedbackActivity.NOTIFICATION_ID, + NotificationCompat.Builder(this, FEEDBACK_CHANNEL_ID) + .setSmallIcon(R.drawable.ic_tile_icon) + .setContentTitle(getString(if (failed) R.string.feedback_failed_title else R.string.feedback_title, dest.name)) + .setContentText(getString(if (failed) R.string.feedback_notification_failed else R.string.feedback_notification)) + .setContentIntent(pending(FEEDBACK_REQUEST_OPEN, if (failed) SpeakerFeedbackActivity.ANSWER_FAILED else null)) + .apply { + if (!failed) { + addAction(0, getString(R.string.feedback_works), pending(FEEDBACK_REQUEST_WORKS, SpeakerFeedbackActivity.ANSWER_WORKS)) + addAction(0, getString(R.string.feedback_problem), pending(FEEDBACK_REQUEST_PROBLEM, SpeakerFeedbackActivity.ANSWER_PROBLEM)) + } + } + .setAutoCancel(true) + .setOnlyAlertOnce(true) + .build() + ) + } + /** One job per destination, so speakers can be added or removed while casting. */ private val destinationJobs = java.util.concurrent.ConcurrentHashMap() 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) + 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) "Google Cast" -> startGoogleCastSession(dest) @@ -650,6 +766,18 @@ class AudioCastService : Service() { } } } + // After a minute of playing, ask once whether the speaker works (see SpeakerFeedback). + if (SpeakerFeedback.isAskable(dest.platform)) scope.launch { askAboutSpeakerLater(dest) } + 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 } /** @@ -664,9 +792,10 @@ 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) - PacketLogger.log(PacketDirection.OUT, PacketType.HANDSHAKE, "Added ${dest.name} to the cast") + 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", device = dest.host) _metadata.value?.let { sendMetadata(it) } updateNotification() } @@ -684,7 +813,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() } @@ -706,6 +835,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 @@ -730,7 +863,10 @@ 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) val responseHeaders = StringBuilder() responseHeaders.append("HTTP/1.1 200 OK\r\n") @@ -749,6 +885,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 } @@ -771,17 +908,27 @@ class AudioCastService : Service() { } output.write(header.array()) - audioBufferFlow.collect { buffer -> + 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) {} } } @@ -794,6 +941,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 @@ -801,45 +1019,34 @@ class AudioCastService : Service() { val streamUrl = "http://$myIp:$STREAM_PORT/stream.wav" try { - try { - val stopBody = """ - - - 0 - - - """.trimIndent() - client.post(controlUrl) { - header("SoapAction", "\"urn:schemas-upnp-org:service:AVTransport:1#Stop\"") - contentType(ContentType.parse("text/xml; charset=utf-8")) - setBody(stopBody) - } - } 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) 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 } } @@ -872,14 +1079,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 @@ -895,7 +1102,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 @@ -945,7 +1152,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 @@ -962,7 +1169,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) } @@ -971,7 +1178,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. @@ -979,7 +1187,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() @@ -988,7 +1196,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) { @@ -1037,7 +1245,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, @@ -1230,14 +1438,15 @@ 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") - audioBufferFlow.collect { streamer.send(it) } + "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)) } } } catch (e: CancellationException) { 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 } } @@ -1375,8 +1584,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) {} @@ -1416,26 +1626,30 @@ 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 - PacketLogger.log(PacketDirection.OUT, PacketType.HANDSHAKE, "Audio socket connected to ${dest.name} (${dest.host}:${dest.port})") + 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") { 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 } + // 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 @@ -1443,8 +1657,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 @@ -1473,9 +1688,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}") + 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) } } @@ -1619,14 +1837,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() } @@ -1641,7 +1862,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) } } } @@ -1659,18 +1880,81 @@ 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()) + /** 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) } + + /** 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 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) { + sharedPreferences.edit().putInt(speakerKey(host, "delay"), delayMs).apply() val current = _activeDestinations.value.toMutableList() val index = current.indexOfFirst { it.host == host } if (index != -1) { @@ -1747,6 +2031,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. @@ -1762,18 +2047,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) { @@ -1795,20 +2080,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) - } + if (configFor(dest).dlnaPlayAfterSetUri != false) dlnaSoap(dest, avUrl, "AVTransport", "Play", playBody) + } catch (e: CancellationException) { + throw e } catch (e: Exception) { Log.e(TAG, "Failed to update DLNA metadata: ${e.message}") } @@ -1873,7 +2152,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() @@ -1885,7 +2164,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 @@ -1901,7 +2180,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) } @@ -1909,10 +2188,13 @@ 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@{ - 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) { @@ -1921,6 +2203,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 @@ -1930,7 +2223,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) } } @@ -1990,6 +2283,7 @@ class AudioCastService : Service() { } private fun cleanupSession() { + cancelSleepTimer() val destinations = _activeDestinations.value.toList() val teardownJobs = stopRemoteSessions(destinations) releaseWakeLock() @@ -2226,6 +2520,10 @@ class AudioCastService : Service() { private const val TAG = "AudioCastService" private const val NOTIFICATION_ID = 1 private const val NOTIFICATION_CHANNEL_ID = "AudioCastChannel" + private const val FEEDBACK_CHANNEL_ID = "SpeakerFeedback" + private const val FEEDBACK_REQUEST_OPEN = 71 + private const val FEEDBACK_REQUEST_WORKS = 72 + private const val FEEDBACK_REQUEST_PROBLEM = 73 const val ACTION_START = "com.aria.ariacast.ACTION_START" const val ACTION_START_SOURCE = "com.aria.ariacast.ACTION_START_SOURCE" const val EXTRA_SOURCE = "com.aria.ariacast.EXTRA_SOURCE" @@ -2273,6 +2571,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/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/MainActivity.kt b/app/src/main/java/com/aria/ariacast/MainActivity.kt index fb90dd4a..fe9b04ce 100644 --- a/app/src/main/java/com/aria/ariacast/MainActivity.kt +++ b/app/src/main/java/com/aria/ariacast/MainActivity.kt @@ -230,6 +230,7 @@ class MainActivity : ComponentActivity(), AppController, PluginHost { override fun onStart() { super.onStart() + com.aria.ariacast.ui.AppVisibility.visible = true bindService(Intent(this, AudioCastService::class.java), connection, Context.BIND_AUTO_CREATE) discoveryManager.startDiscovery() } @@ -244,6 +245,7 @@ class MainActivity : ComponentActivity(), AppController, PluginHost { override fun onStop() { super.onStop() + com.aria.ariacast.ui.AppVisibility.visible = false if (isBound) { unbindService(connection) isBound = false diff --git a/app/src/main/java/com/aria/ariacast/PacketLogger.kt b/app/src/main/java/com/aria/ariacast/PacketLogger.kt index 522ec2de..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 } @@ -15,13 +18,33 @@ 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, + /** 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() @@ -32,39 +55,78 @@ 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] 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, direction = direction, type = type, message = message, - payloadSize = payloadSize + 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) { + 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/crash/CrashReport.kt b/app/src/main/java/com/aria/ariacast/crash/CrashReport.kt new file mode 100644 index 00000000..7e9ff5b4 --- /dev/null +++ b/app/src/main/java/com/aria/ariacast/crash/CrashReport.kt @@ -0,0 +1,24 @@ +package com.aria.ariacast.crash + +import java.io.PrintWriter +import java.io.StringWriter + +/** What a crash report says. Pure, so it can be tested; [CrashReporter] does the catching. */ +object CrashReport { + /** A very deep trace (a stack overflow) would not fit through an Intent; the top of it is what matters. */ + const val MAX_CHARS = 30_000 + + fun format(error: Throwable, threadName: String, app: String, device: String, time: String): String { + val trace = StringWriter().also { error.printStackTrace(PrintWriter(it)) }.toString() + val text = buildString { + appendLine("AriaCast crash report") + appendLine("Time: $time") + appendLine("App: $app") + appendLine("Device: $device") + appendLine("Thread: $threadName") + appendLine() + append(trace) + } + return if (text.length <= MAX_CHARS) text else text.take(MAX_CHARS) + "\n... (cut)" + } +} diff --git a/app/src/main/java/com/aria/ariacast/crash/CrashReportActivity.kt b/app/src/main/java/com/aria/ariacast/crash/CrashReportActivity.kt new file mode 100644 index 00000000..d00f8d56 --- /dev/null +++ b/app/src/main/java/com/aria/ariacast/crash/CrashReportActivity.kt @@ -0,0 +1,49 @@ +package com.aria.ariacast.crash + +import android.app.Activity +import android.content.Intent +import android.graphics.Typeface +import android.os.Bundle +import android.view.Gravity +import android.view.ViewGroup +import android.widget.Button +import android.widget.LinearLayout +import android.widget.ScrollView +import android.widget.TextView +import com.aria.ariacast.R + +/** + * Shows a crash report and lets it be shared. Plain views and no theme tricks on purpose: this is + * what has to work when everything else does not. It runs in the ":crash" process. + */ +class CrashReportActivity : Activity() { + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + val report = intent.getStringExtra(EXTRA_REPORT) ?: getString(R.string.crash_no_report) + val pad = (16 * resources.displayMetrics.density).toInt() + + val title = TextView(this).apply { text = getString(R.string.crash_title); textSize = 20f; setTypeface(typeface, Typeface.BOLD) } + val body = TextView(this).apply { text = report; textSize = 11f; typeface = Typeface.MONOSPACE; setTextIsSelectable(true) } + val share = Button(this).apply { + text = getString(R.string.crash_share) + setOnClickListener { + val send = Intent(Intent.ACTION_SEND).setType("text/plain").putExtra(Intent.EXTRA_TEXT, report) + startActivity(Intent.createChooser(send, getString(R.string.crash_share))) + } + } + val close = Button(this).apply { text = getString(R.string.crash_close); setOnClickListener { finishAndRemoveTask() } } + val buttons = LinearLayout(this).apply { gravity = Gravity.END; addView(share); addView(close) } + + setContentView(LinearLayout(this).apply { + orientation = LinearLayout.VERTICAL + setPadding(pad, pad * 2, pad, pad) + addView(title) + addView(ScrollView(this@CrashReportActivity).apply { addView(body) }, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f)) + addView(buttons) + }) + } + + companion object { + const val EXTRA_REPORT = "com.aria.ariacast.CRASH_REPORT" + } +} diff --git a/app/src/main/java/com/aria/ariacast/crash/CrashReporter.kt b/app/src/main/java/com/aria/ariacast/crash/CrashReporter.kt new file mode 100644 index 00000000..149d0a07 --- /dev/null +++ b/app/src/main/java/com/aria/ariacast/crash/CrashReporter.kt @@ -0,0 +1,44 @@ +package com.aria.ariacast.crash + +import android.app.Application +import android.content.Intent +import android.content.pm.ApplicationInfo +import android.os.Build +import java.text.SimpleDateFormat +import java.util.Date +import java.util.Locale + +/** + * In a debug build, an uncaught crash opens a screen with the stack trace and a Share button, + * so a tester without a computer can say why the app stopped. The screen runs in its own + * process (see [CrashReportActivity]), which is what lets it stay up while this one dies. + * Release builds are left alone. + */ +object CrashReporter { + fun install(app: Application) { + if (app.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE == 0) return + val previous = Thread.getDefaultUncaughtExceptionHandler() + Thread.setDefaultUncaughtExceptionHandler { thread, error -> + try { + val version = runCatching { app.packageManager.getPackageInfo(app.packageName, 0).versionName }.getOrNull() + val report = CrashReport.format( + error, thread.name, + app = "${app.packageName} ${version ?: "?"}", + device = "${Build.MANUFACTURER} ${Build.MODEL}, Android ${Build.VERSION.RELEASE} (API ${Build.VERSION.SDK_INT})", + time = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).format(Date()), + ) + app.startActivity( + Intent(app, CrashReportActivity::class.java) + .putExtra(CrashReportActivity.EXTRA_REPORT, report) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK) + ) + } catch (_: Throwable) { + // Reporting must never hide the crash itself. + } + previous?.uncaughtException(thread, error) + } + } + + /** The crash screen lives in a second process, which must not start the app a second time. */ + fun isCrashProcess(): Boolean = Application.getProcessName().endsWith(":crash") +} 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..32ecf0dc 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) { @@ -77,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/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..809057f0 --- /dev/null +++ b/app/src/main/java/com/aria/ariacast/quirks/DeviceQuirks.kt @@ -0,0 +1,57 @@ +package com.aria.ariacast.quirks + +import com.aria.ariacast.ExtraFields +import java.util.Locale + +/** + * 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(", ") +} + +object DeviceQuirks { + /** 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 one entry that fits [device] best, if any: the report of a device is counted there. The first + * in the list wins a tie. + */ + fun bestMatch(device: DeviceIdentity): KnownSpeaker? = all.maxByOrNull { it.match.specificity(device) }?.takeIf { 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..a3d7f896 --- /dev/null +++ b/app/src/main/java/com/aria/ariacast/quirks/KnownSpeakers.kt @@ -0,0 +1,234 @@ +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 Status(val id: String, val label: String) { + /** Plays as expected. */ + SUPPORTED("supported", "Supported"), + + /** Plays, with something the user should know about (see the entry's symptoms). */ + QUIRKS("quirks", "Supported with quirks"), + + /** Does not play, or AriaCast has no way in (Bluetooth only, cloud only). The symptoms say which. */ + UNSUPPORTED("unsupported", "Unsupported"), + ; + + 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. The known-speakers bot applies the same rule (tests/resources/matching-cases.json holds the + * cases both must answer alike). + */ +data class Match(val platform: String?, val mentions: List) { + /** + * How well this fits [device], or 0 if it does not. A word found in the name or model scores its + * length, so "wiim pro" beats "wiim"; a word found only in the maker's name scores 1, so a model + * word always beats a maker's. + */ + fun specificity(device: DeviceIdentity): Int { + if (platform != null && device.platform != platform) return 0 + val own = listOfNotNull(device.name, device.model).joinToString(" ").lowercase() + val best = mentions.filter { own.contains(it) }.maxOfOrNull { it.length } ?: 0 + if (best > 0) return best + val maker = device.manufacturer?.lowercase().orEmpty() + return if (mentions.any { maker.contains(it) }) 1 else 0 + } + + fun appliesTo(device: DeviceIdentity): Boolean = specificity(device) > 0 +} + +/** + * One entry of the list of speakers we know something about, kept in the AriaCast/known-speakers + * repository. An entry exists because somebody reported it or a maintainer checked it. + */ +data class KnownSpeaker( + val id: String, + /** Brand and, where known, the model it was seen on. */ + val speaker: String, + val protocol: String, + val status: Status, + 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(), + /** How many reports were counted per status; the status above follows the most reported one. */ + val reports: Map = emptyMap(), + /** A maintainer curated this entry: reports are counted but do not change it. */ + val locked: Boolean = false, +) { + 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 = 2 + const val MAX_REPORTS = 1_000_000 + 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" + Status.of(e.status) == null -> "unknown status" + 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), + status = Status.of(e.status)!!, + 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(), + reports = e.reports.mapNotNull { (k, v) -> Status.of(k)?.takeIf { v in 0..MAX_REPORTS }?.let { it to v } }.toMap(), + locked = e.locked, + ) + } + 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 status: 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, + val reports: Map = emptyMap(), + val locked: Boolean = false, + ) + + @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..5a1deb3b --- /dev/null +++ b/app/src/main/java/com/aria/ariacast/quirks/KnownSpeakersStore.kt @@ -0,0 +1,49 @@ +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 last one downloaded from the project (see + * [SpeakerListSync]), kept on the phone. The app ships no copy, so before the first download the + * list is empty. A downloaded list only ever replaces the one in use 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 CACHE = "speakers-synced.json" + + @Volatile + var current: KnownSpeakersFile = KnownSpeakersFile(0, "", emptyList()) + private set + + /** Loads the list downloaded last time, if any. Safe to call more than once. */ + @Synchronized + fun init(context: Context) { + if (current.speakers.isNotEmpty()) return + val cached = cacheFile(context).takeIf { it.exists() }?.let { KnownSpeakersFile.parse(runCatching { it.readText() }.getOrDefault("")) } + current = cached ?: KnownSpeakersFile(0, "", emptyList()) + 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/SpeakerFeedback.kt b/app/src/main/java/com/aria/ariacast/quirks/SpeakerFeedback.kt new file mode 100644 index 00000000..65e9f37f --- /dev/null +++ b/app/src/main/java/com/aria/ariacast/quirks/SpeakerFeedback.kt @@ -0,0 +1,73 @@ +package com.aria.ariacast.quirks + +import android.content.SharedPreferences + +/** + * The question asked once about each speaker, after a minute of casting to it: does it work? + * What to ask and when lives here so it can be tested; showing it is [com.aria.ariacast.ui.SpeakerFeedbackActivity]. + */ +object SpeakerFeedback { + /** How long a speaker must have been playing before it is asked about. */ + const val ASK_AFTER_MS = 60_000L + + /** + * A speaker is told apart by its protocol and the name it goes by. An address changes with the + * router; a name seldom does. + */ + fun key(platform: String?, name: String) = "${platform ?: "-"}|${name.trim().lowercase()}" + + /** + * Only things that are speakers are asked about. An AriaCast receiver, a Snapcast or VBAN server + * or a Sendspin server is software on a phone, a computer or a server: there is no speaker to + * judge, and a list of speakers has no place for it. + */ + fun isAskable(platform: String?) = platform in ASKABLE + + private val ASKABLE = setOf("AirPlay", "AirPlay2", "DLNA", "Google Cast") + + /** Ask when the minute is up and the speaker is still playing in a cast, and was never asked. */ + fun shouldAsk(casting: Boolean, stillInCast: Boolean, alreadyAsked: Boolean, platform: String?) = + casting && stillInCast && !alreadyAsked && isAskable(platform) + + /** + * A cast that fails in the first minute: ask whether to report it, but only when the speaker is + * the only one in the cast, since a failure does not say which of several speakers it was. + */ + fun shouldAskAfterFailure(speakersInCast: Int, alreadyAsked: Boolean, platform: String?) = + speakersInCast == 1 && !alreadyAsked && isAskable(platform) + + /** + * After "it works": offer to add the speaker to the public list unless the list already says it + * is supported ([best] is the entry the speaker's report would be counted in, if any). One more "it works" for a speaker everybody knows adds little, and sending it + * takes a GitHub account. + */ + fun offerSharingAfterWorks(best: KnownSpeaker?) = best?.status != Status.SUPPORTED + + /** The word of the report form's dropdown for a status. */ + fun formLabel(status: Status) = when (status) { + Status.SUPPORTED -> SpeakerIssue.STATUS_SUPPORTED + Status.QUIRKS -> SpeakerIssue.STATUS_QUIRKS + Status.UNSUPPORTED -> SpeakerIssue.STATUS_UNSUPPORTED + } +} + +/** + * What has been asked and answered, kept on the phone. Nothing here is sent anywhere: an answer + * only leaves the phone if the user then opens a report. + */ +class FeedbackLedger(private val read: (String) -> String?, private val write: (String, String) -> Unit) { + fun asked(key: String) = read("asked.$key") != null + + fun markAsked(key: String, atMs: Long) = write("asked.$key", atMs.toString()) + + fun record(key: String, status: Status) = write("answer.$key", status.id) + + fun answer(key: String): Status? = Status.of(read("answer.$key")) + + companion object { + fun of(prefs: SharedPreferences) = FeedbackLedger( + read = { prefs.getString("fb.$it", null) }, + write = { k, v -> prefs.edit().putString("fb.$k", v).apply() }, + ) + } +} 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..14d1c968 --- /dev/null +++ b/app/src/main/java/com/aria/ariacast/quirks/SpeakerIssue.kt @@ -0,0 +1,67 @@ +package com.aria.ariacast.quirks + +import java.net.URLEncoder + +/** + * The address of a pre-filled "Speaker report" issue in the AriaCast/known-speakers repository. The + * field names are the ids in that repository's .github/ISSUE_TEMPLATE/speaker-report.yml, and the + * dropdown values are its option labels (a test keeps a copy of that form to check them). + */ +object SpeakerIssue { + private const val NEW_ISSUE = "https://github.com/AriaCast/known-speakers/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 + + /** What the user wrote about the problem; the rest of the address is cut before this is. */ + const val MAX_SYMPTOMS = 1000 + + const val STATUS_SUPPORTED = "Supported" + const val STATUS_QUIRKS = "Supported with quirks" + const val STATUS_UNSUPPORTED = "Unsupported" + + /** 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" + null -> "No local protocol" + else -> "Other" + } + + /** + * The name to propose: brand and model if the speaker said them, else nothing. The name its owner + * gave it ("Studio") says nothing about what it is, and the list is recognised by model: the form + * asks the reporter to write it. + */ + fun speakerName(identity: DeviceIdentity): String = + listOfNotNull(identity.manufacturer, identity.model).joinToString(" ").trim() + + fun url(identity: DeviceIdentity, details: String, appVersion: String?, status: String? = null, symptoms: String? = null): String { + fun build(details: String): String { + val fields = listOfNotNull( + "template" to TEMPLATE, + speakerName(identity).takeIf { it.isNotEmpty() }?.let { "title" to "Speaker: $it" }, + speakerName(identity).takeIf { it.isNotEmpty() }?.let { "speaker" to it }, + "protocol" to protocolLabel(identity.platform), + status?.let { "status" to it }, + symptoms?.trim()?.takeIf { it.isNotEmpty() }?.let { "symptoms" to it.take(MAX_SYMPTOMS) }, + "details" 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/SpeakerListSync.kt b/app/src/main/java/com/aria/ariacast/quirks/SpeakerListSync.kt new file mode 100644 index 00000000..38b39577 --- /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 speakers.json from the project's + * AriaCast/known-speakers 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/known-speakers/main/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/quirks/SpeakerReport.kt b/app/src/main/java/com/aria/ariacast/quirks/SpeakerReport.kt new file mode 100644 index 00000000..4b61ed17 --- /dev/null +++ b/app/src/main/java/com/aria/ariacast/quirks/SpeakerReport.kt @@ -0,0 +1,80 @@ +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 = 500 + + 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, + ) + + /** Who the speaker is and what is known about it, without the log. Addresses are shortened. */ + fun summary( + context: Context, + identity: DeviceIdentity, + known: List, + ): String = buildString { + 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.status.label}") } + } + 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()) { + 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/scan/NetworkScanner.kt b/app/src/main/java/com/aria/ariacast/scan/NetworkScanner.kt new file mode 100644 index 00000000..9b7aa1ae --- /dev/null +++ b/app/src/main/java/com/aria/ariacast/scan/NetworkScanner.kt @@ -0,0 +1,116 @@ +package com.aria.ariacast.scan + +import android.content.Context +import android.net.nsd.NsdManager +import android.net.nsd.NsdServiceInfo +import android.util.Log +import com.aria.ariacast.quirks.SpeakerListSync +import java.io.IOException +import java.net.DatagramPacket +import java.net.DatagramSocket +import java.net.HttpURLConnection +import java.net.InetAddress +import java.net.URI +import java.util.concurrent.CopyOnWriteArrayList +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitAll +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.delay +import kotlinx.coroutines.withContext + +/** + * One look at the local network for devices AriaCast cannot play to, when the user asks. It + * sends a UPnP search and listens for the mDNS service types in [ScanParsing.MDNS_TYPES]; it reads + * a device's description only from the address that answered, and keeps nothing afterwards. + */ +class NetworkScanner(context: Context) { + private val nsd = context.getSystemService(Context.NSD_SERVICE) as NsdManager + + suspend fun scan(durationMs: Long = SCAN_MS, usableNames: Collection = emptyList()): List = coroutineScope { + val mdns = CopyOnWriteArrayList() + val listeners = startMdns(mdns) + try { + val ssdp = async(Dispatchers.IO) { searchSsdp(durationMs) } + delay(durationMs) + ScanParsing.otherDevices(ssdp.await(), mdns.toList(), usableNames) + } finally { + listeners.forEach { runCatching { nsd.stopServiceDiscovery(it) } } + } + } + + private fun startMdns(found: MutableList): List = + ScanParsing.MDNS_TYPES.keys.mapNotNull { type -> + val listener = object : NsdManager.DiscoveryListener { + override fun onServiceFound(info: NsdServiceInfo) { found += MdnsFound(info.serviceName.orEmpty(), type) } + override fun onServiceLost(info: NsdServiceInfo) {} + override fun onDiscoveryStarted(serviceType: String) {} + override fun onDiscoveryStopped(serviceType: String) {} + override fun onStartDiscoveryFailed(serviceType: String, errorCode: Int) { Log.d(TAG, "mDNS $serviceType: error $errorCode") } + override fun onStopDiscoveryFailed(serviceType: String, errorCode: Int) {} + } + try { + nsd.discoverServices(type, NsdManager.PROTOCOL_DNS_SD, listener) + listener + } catch (e: Exception) { + Log.d(TAG, "mDNS $type: ${e.message}") + null + } + } + + private suspend fun searchSsdp(durationMs: Long): List = withContext(Dispatchers.IO) { + val replies = linkedMapOf>() // location -> (answering address, reply) + try { + DatagramSocket().use { socket -> + socket.soTimeout = 1000 + val query = "M-SEARCH * HTTP/1.1\r\nHOST: 239.255.255.250:1900\r\nMAN: \"ssdp:discover\"\r\nMX: 3\r\nST: ssdp:all\r\n\r\n".toByteArray() + socket.send(DatagramPacket(query, query.size, InetAddress.getByName("239.255.255.250"), 1900)) + val end = System.currentTimeMillis() + durationMs - 1500 + val buffer = ByteArray(2048) + while (System.currentTimeMillis() < end && replies.size < MAX_DEVICES) { + val packet = DatagramPacket(buffer, buffer.size) + try { socket.receive(packet) } catch (_: java.net.SocketTimeoutException) { continue } + val host = packet.address.hostAddress ?: continue + ScanParsing.ssdpReply(String(packet.data, 0, packet.length))?.let { replies.putIfAbsent(it.location, host to it) } + } + } + } catch (e: Exception) { + Log.d(TAG, "SSDP: ${e.message}") + } + replies.values.map { (host, reply) -> async { describe(host, reply) } }.awaitAll().filterNotNull() + } + + /** The description a device points to, but only if it is on the address that answered. */ + private fun describe(host: String, reply: SsdpReply): SsdpDevice? = try { + val uri = URI(reply.location) + if ((uri.scheme != "http") || uri.host != host) { + null + } else { + val connection = uri.toURL().openConnection() as HttpURLConnection + try { + connection.connectTimeout = 2000 + connection.readTimeout = 2000 + connection.instanceFollowRedirects = false + if (connection.responseCode != HttpURLConnection.HTTP_OK || connection.contentLengthLong > ScanParsing.MAX_DESCRIPTION_BYTES) { + null + } else { + // Throws if the description is longer than allowed, which ends up as "not a device". + val xml = connection.inputStream.use { SpeakerListSync.readBounded(it, ScanParsing.MAX_DESCRIPTION_BYTES) } + ScanParsing.description(xml, host, reply.server) + } + } finally { + connection.disconnect() + } + } + } catch (e: IOException) { + null + } catch (e: Exception) { + null + } + + companion object { + private const val TAG = "NetworkScanner" + const val SCAN_MS = 8_000L + private const val MAX_DEVICES = 60 + } +} diff --git a/app/src/main/java/com/aria/ariacast/scan/ScanParsing.kt b/app/src/main/java/com/aria/ariacast/scan/ScanParsing.kt new file mode 100644 index 00000000..3f68083b --- /dev/null +++ b/app/src/main/java/com/aria/ariacast/scan/ScanParsing.kt @@ -0,0 +1,142 @@ +package com.aria.ariacast.scan + +import com.aria.ariacast.dlna.Dlna +import com.aria.ariacast.quirks.DeviceIdentity +import com.aria.ariacast.quirks.SpeakerReport + +/** An answer to an SSDP search: where the device describes itself, and what it says it is. */ +data class SsdpReply(val location: String, val server: String?) + +/** What a device's UPnP description says. All of it is the device's own text, so it is only shown and compared. */ +data class SsdpDevice( + val host: String, + val friendlyName: String, + val manufacturer: String?, + val modelName: String?, + val deviceType: String?, + val services: List, + val server: String?, +) { + /** A DLNA renderer is something AriaCast already plays to; it is not a missing speaker. */ + val isRenderer: Boolean get() = services.any { it.contains(":service:AVTransport:") } +} + +/** A service name announced over mDNS, as the network gave it. */ +data class MdnsFound(val name: String, val type: String) + +/** A device on the network that AriaCast has no way to play to, as far as a scan can tell. */ +data class OtherDevice( + val name: String, + val manufacturer: String? = null, + val model: String? = null, + val mdnsTypes: List = emptyList(), + val deviceType: String? = null, + val upnpServices: List = emptyList(), + val server: String? = null, + val host: String? = null, +) + +/** Reading what a scan finds. Pure, so it can be tested without a network. */ +object ScanParsing { + const val MAX_DESCRIPTION_BYTES = 64 * 1024 + + /** + * mDNS service types worth looking for: what speakers and their ecosystems announce, other than + * what AriaCast already plays to (AirPlay, Google Cast, AriaCast, Snapcast). A type nobody on the + * network announces just finds nothing. + */ + val MDNS_TYPES: Map = linkedMapOf( + "_spotify-connect._tcp" to "Spotify Connect", + "_sonos._tcp" to "Sonos", + "_amzn-wplay._tcp" to "Amazon", + "_hap._tcp" to "HomeKit", + "_heos-audio._tcp" to "HEOS", + "_soundtouch._tcp" to "Bose SoundTouch", + "_mediaremotetv._tcp" to "Apple TV", + "_companion-link._tcp" to "Apple", + ) + + private fun clean(text: String?, max: Int) = + text?.filter { it >= ' ' && it != '\u007f' }?.trim()?.take(max)?.takeIf { it.isNotEmpty() } + + /** The LOCATION and SERVER of an SSDP answer, or null if it does not say where the device is. */ + fun ssdpReply(text: String): SsdpReply? { + val headers = text.split("\r\n", "\n").mapNotNull { line -> + val i = line.indexOf(':') + if (i <= 0) null else line.substring(0, i).trim().lowercase() to line.substring(i + 1).trim() + }.toMap() + val location = clean(headers["location"], 300) ?: return null + return SsdpReply(location, clean(headers["server"], 120)) + } + + /** The device a UPnP description is about, or null if it has no name. */ + fun description(xml: String, host: String, server: String?): SsdpDevice? { + if (xml.length > MAX_DESCRIPTION_BYTES) return null + fun tag(t: String, src: String = xml) = Regex("<$t>([\\s\\S]*?)").find(src)?.groupValues?.get(1)?.let(Dlna::xmlUnescape) + val name = clean(tag("friendlyName"), 80) ?: return null + val services = Regex("([\\s\\S]*?)").findAll(xml) + .mapNotNull { clean(Dlna.xmlUnescape(it.groupValues[1]), 80) }.distinct().take(12).toList() + return SsdpDevice( + host = host, + friendlyName = name, + manufacturer = clean(tag("manufacturer"), 60), + modelName = clean(tag("modelName"), 60), + deviceType = clean(tag("deviceType"), 80), + services = services, + server = server, + ) + } + + /** + * What the scan found, as devices AriaCast cannot play to: UPnP devices that are not renderers + * and mDNS services of the other types, with the two joined when they share a name, and without + * anything whose name is one of [usableNames] (a speaker the app already lists). + */ + fun otherDevices(ssdp: List, mdns: List, usableNames: Collection = emptyList()): List { + val usable = usableNames.map { it.trim().lowercase() }.filter { it.isNotEmpty() } + fun isUsable(name: String) = usable.any { u -> name.lowercase().let { n -> n == u || n.contains(u) || u.contains(n) } } + + val byName = linkedMapOf() + mdns.groupBy { clean(it.name, 60)?.lowercase() ?: "" }.forEach { (key, found) -> + if (key.isEmpty()) return@forEach + byName[key] = OtherDevice(name = clean(found.first().name, 60)!!, mdnsTypes = found.map { it.type }.distinct().sorted()) + } + ssdp.filter { !it.isRenderer }.forEach { d -> + val key = d.friendlyName.lowercase() + val joined = byName[key] ?: byName.entries.firstOrNull { (k, _) -> key.contains(k) || k.contains(key) }?.value + val device = OtherDevice( + name = joined?.name ?: d.friendlyName, manufacturer = d.manufacturer, model = d.modelName, + mdnsTypes = joined?.mdnsTypes ?: emptyList(), deviceType = d.deviceType, upnpServices = d.services, + server = d.server, host = d.host, + ) + byName.remove(joined?.name?.lowercase()) + byName[key] = device + } + return byName.values.filterNot { isUsable(it.name) }.sortedBy { it.name.lowercase() } + } + + /** The identity the report form uses for a device: no protocol, since there is none we can play to. */ + fun identity(d: OtherDevice) = DeviceIdentity(platform = null, name = d.name, model = d.model, manufacturer = d.manufacturer) + + /** Everything the scan learned about a device, for a report. Addresses are shortened. */ + fun fingerprint(d: OtherDevice): String = buildString { + appendLine("Found by a network scan, not as a speaker AriaCast can play to.") + appendLine("Name: ${d.name}") + d.manufacturer?.let { appendLine("Manufacturer: $it") } + d.model?.let { appendLine("Model: $it") } + if (d.mdnsTypes.isNotEmpty()) appendLine("mDNS: ${d.mdnsTypes.joinToString(", ")}") + d.deviceType?.let { appendLine("UPnP device type: $it") } + if (d.upnpServices.isNotEmpty()) appendLine("UPnP services: ${d.upnpServices.joinToString(", ")}") + d.server?.let { appendLine("Server: $it") } + d.host?.let { appendLine("Address: $it") } + }.trimEnd().let(SpeakerReport::maskAddresses) + + /** A short line for the list: what kind of thing it announced. */ + fun summary(d: OtherDevice): String { + val labels = d.mdnsTypes.mapNotNull { MDNS_TYPES[it] } + return listOfNotNull( + labels.takeIf { it.isNotEmpty() }?.joinToString(", "), + listOfNotNull(d.manufacturer, d.model).joinToString(" ").takeIf { it.isNotBlank() }, + ).joinToString(" ยท ").ifEmpty { "UPnP" } + } +} 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/AppVisibility.kt b/app/src/main/java/com/aria/ariacast/ui/AppVisibility.kt new file mode 100644 index 00000000..7dccc69b --- /dev/null +++ b/app/src/main/java/com/aria/ariacast/ui/AppVisibility.kt @@ -0,0 +1,10 @@ +package com.aria.ariacast.ui + +/** + * Whether one of the app's screens is on show. A background service may only open a window while + * this is true; otherwise it has to use a notification. + */ +object AppVisibility { + @Volatile + var visible = false +} 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..1b08bc36 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(controller, onBack = back) else -> {} } } diff --git a/app/src/main/java/com/aria/ariacast/ui/SpeakerFeedbackActivity.kt b/app/src/main/java/com/aria/ariacast/ui/SpeakerFeedbackActivity.kt new file mode 100644 index 00000000..2ca1376f --- /dev/null +++ b/app/src/main/java/com/aria/ariacast/ui/SpeakerFeedbackActivity.kt @@ -0,0 +1,189 @@ +package com.aria.ariacast.ui + +import android.content.Context +import android.os.Bundle +import android.widget.Toast +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.selection.selectableGroup +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.RadioButton +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import androidx.core.app.NotificationManagerCompat +import com.aria.ariacast.AudioCastService +import com.aria.ariacast.R +import com.aria.ariacast.quirks.DeviceIdentity +import com.aria.ariacast.quirks.DeviceQuirks +import com.aria.ariacast.quirks.FeedbackLedger +import com.aria.ariacast.quirks.SpeakerFeedback +import com.aria.ariacast.quirks.Status +import com.aria.ariacast.ui.theme.AriaTheme + +/** + * "Does it work?", asked once about a speaker after a minute of casting to it. It is a plain dialog + * over whatever is on screen (or a notification when the app is closed, which opens this). The + * answer stays on the phone; only if the user chooses to report does anything open on GitHub. + */ +class SpeakerFeedbackActivity : ComponentActivity() { + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + val name = intent.getStringExtra(EXTRA_NAME) + val host = intent.getStringExtra(EXTRA_HOST) + if (name == null || host == null) { + finish() + return + } + // Answering from the notification's buttons is answering: the notification goes. + NotificationManagerCompat.from(this).cancel(NOTIFICATION_ID) + val platform = intent.getStringExtra(EXTRA_PLATFORM) + val extra = intent.getStringExtra(EXTRA_EXTRA) + val start = intent.getStringExtra(EXTRA_ANSWER) + val castState = intent.getStringExtra(EXTRA_CAST_STATE) + setContent { AriaTheme { FeedbackFlow(platform, name, host, extra, start, castState, onFinish = ::finish) } } + } + + companion object { + const val EXTRA_PLATFORM = "com.aria.ariacast.FEEDBACK_PLATFORM" + const val EXTRA_NAME = "com.aria.ariacast.FEEDBACK_NAME" + const val EXTRA_HOST = "com.aria.ariacast.FEEDBACK_HOST" + const val EXTRA_EXTRA = "com.aria.ariacast.FEEDBACK_EXTRA" + + /** The cast's state when it was asked, so a report made here still says what the cast was doing. */ + const val EXTRA_CAST_STATE = "com.aria.ariacast.FEEDBACK_CAST_STATE" + + /** Set by the notification's buttons: [ANSWER_WORKS] or [ANSWER_PROBLEM]. */ + const val EXTRA_ANSWER = "com.aria.ariacast.FEEDBACK_ANSWER" + const val ANSWER_WORKS = "works" + const val ANSWER_PROBLEM = "problem" + + /** The cast failed: the question is whether to report it, not whether it works. */ + const val ANSWER_FAILED = "failed" + const val NOTIFICATION_ID = 7 + } +} + +private enum class Step { NONE, ASK, FAILED, PROBLEM, SHARE } + +@Composable +private fun FeedbackFlow(platform: String?, name: String, host: String, extra: String?, start: String?, castState: String?, onFinish: () -> Unit) { + val context = LocalContext.current + val ledger = remember { FeedbackLedger.of(context.getSharedPreferences(AudioCastService.PREFS_NAME, Context.MODE_PRIVATE)) } + val key = remember { SpeakerFeedback.key(platform, name) } + val identity = remember { DeviceIdentity.of(platform, name, extra) } + var step by remember { mutableStateOf(when (start) { null -> Step.ASK; "failed" -> Step.FAILED; else -> Step.NONE }) } + // After a failed cast the user has already said it does not work; "it plays but" is not on offer. + val failed = start == "failed" + + fun works(): Step { + ledger.record(key, Status.SUPPORTED) + if (SpeakerFeedback.offerSharingAfterWorks(DeviceQuirks.bestMatch(identity))) return Step.SHARE + Toast.makeText(context, context.getString(R.string.feedback_thanks), Toast.LENGTH_SHORT).show() + onFinish() + return Step.NONE + } + + // A button of the notification already is an answer: go straight to what follows it. + LaunchedEffect(Unit) { + when (start) { + "works" -> step = works() + "problem" -> step = Step.PROBLEM + } + } + + when (step) { + Step.NONE -> Unit + Step.ASK -> AlertDialog( + onDismissRequest = onFinish, + title = { Text(stringResource(R.string.feedback_title, name)) }, + text = { Text(stringResource(R.string.feedback_ask, name)) }, + confirmButton = { TextButton(onClick = { step = works() }) { Text(stringResource(R.string.feedback_works)) } }, + dismissButton = { TextButton(onClick = { step = Step.PROBLEM }) { Text(stringResource(R.string.feedback_problem)) } }, + ) + Step.FAILED -> AlertDialog( + onDismissRequest = onFinish, + title = { Text(stringResource(R.string.feedback_failed_title, name)) }, + text = { Text(stringResource(R.string.feedback_failed_text, name)) }, + confirmButton = { TextButton(onClick = { step = Step.PROBLEM }) { Text(stringResource(R.string.feedback_report)) } }, + dismissButton = { TextButton(onClick = onFinish) { Text(stringResource(R.string.feedback_no_thanks)) } }, + ) + Step.SHARE -> AlertDialog( + onDismissRequest = onFinish, + title = { Text(stringResource(R.string.feedback_share_title)) }, + text = { Text(stringResource(R.string.feedback_share_text, name)) }, + confirmButton = { + TextButton(onClick = { + reportSpeaker(context, null, platform, name, host, extra, SpeakerFeedback.formLabel(Status.SUPPORTED), castState = castState) + onFinish() + }) { Text(stringResource(R.string.feedback_share)) } + }, + dismissButton = { TextButton(onClick = onFinish) { Text(stringResource(R.string.feedback_no_thanks)) } }, + ) + Step.PROBLEM -> ProblemDialog( + initialBroken = failed, + onCancel = onFinish, + onContinue = { status, text -> + ledger.record(key, status) + reportSpeaker(context, null, platform, name, host, extra, SpeakerFeedback.formLabel(status), text, castState) + onFinish() + }, + ) + } +} + +@Composable +private fun ProblemDialog(initialBroken: Boolean, onCancel: () -> Unit, onContinue: (Status, String) -> Unit) { + var broken by remember { mutableStateOf(initialBroken) } + var text by remember { mutableStateOf("") } + AlertDialog( + onDismissRequest = onCancel, + title = { Text(stringResource(R.string.feedback_problem_title)) }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + Column(Modifier.selectableGroup()) { + listOf(false to R.string.feedback_problem_partial, true to R.string.feedback_problem_broken).forEach { (isBroken, label) -> + Row( + Modifier.fillMaxWidth().selectable(selected = broken == isBroken, onClick = { broken = isBroken }, role = Role.RadioButton).padding(vertical = 6.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + RadioButton(selected = broken == isBroken, onClick = null) + Text(stringResource(label), modifier = Modifier.padding(start = 12.dp)) + } + } + } + OutlinedTextField( + value = text, onValueChange = { text = it.take(SPEAKER_NOTE_MAX) }, minLines = 3, + label = { Text(stringResource(R.string.feedback_problem_hint)) }, modifier = Modifier.fillMaxWidth(), + ) + } + }, + // The list asks a speaker that does not simply work to say what happens, so the note is needed. + confirmButton = { + TextButton(enabled = text.isNotBlank(), onClick = { onContinue(if (broken) Status.UNSUPPORTED else Status.QUIRKS, text) }) { + Text(stringResource(R.string.feedback_continue)) + } + }, + dismissButton = { TextButton(onClick = onCancel) { Text(stringResource(R.string.feedback_cancel)) } }, + ) +} + +private const val SPEAKER_NOTE_MAX = 600 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..c7aa57e9 --- /dev/null +++ b/app/src/main/java/com/aria/ariacast/ui/SpeakerReportAction.kt @@ -0,0 +1,96 @@ +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 +import com.aria.ariacast.scan.OtherDevice +import com.aria.ariacast.scan.ScanParsing + +/** + * 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). + */ +private fun reportContext(context: Context, service: AudioCastService?, host: String, castStateFallback: String? = null): 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) + 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(", ") } ?: castStateFallback, + 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, 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. [status] and [symptoms] pre-fill how it works and what happens + * when the user has said so already (see [SpeakerIssue]). + */ +fun reportSpeaker( + context: Context, + service: AudioCastService?, + platform: String?, + name: String, + host: String, + extra: String?, + status: String? = null, + symptoms: String? = null, + castState: String? = null, +) { + val identity = DeviceIdentity.of(platform, name, extra) + val ctx = reportContext(context, service, host, castState) + // The log is for finding out what went wrong: a speaker that works has nothing to explain. + val copyLog = status != SpeakerIssue.STATUS_SUPPORTED + val url = SpeakerIssue.url(identity, SpeakerReport.summary(ctx, identity, DeviceQuirks.matching(identity)), ctx.app.substringAfter(' '), status, symptoms) + if (copyLog) { + 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)) + 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)) +} + +/** Not translated: it goes into a public list written in English. */ +private const val SCAN_SYMPTOMS = "AriaCast does not find it as a speaker." + +/** + * Opens a pre-filled report for a device a scan found but AriaCast cannot play to. How it works is + * left for the user to say; what the scan learned about it is in the details, with addresses shortened. + */ +fun reportOtherDevice(context: Context, device: OtherDevice) { + val identity = ScanParsing.identity(device) + val ctx = reportContext(context, null, device.host.orEmpty()) + val details = SpeakerReport.summary(ctx, identity, emptyList()) + "\n\n" + ScanParsing.fingerprint(device) + val url = SpeakerIssue.url(identity, details, ctx.app.substringAfter(' '), symptoms = SCAN_SYMPTOMS) + 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 81dc3ab8..5d3e02b8 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,14 @@ 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.CastDestination +import com.aria.ariacast.quirks.DeviceIdentity +import com.aria.ariacast.quirks.SpeakerFeedback +import kotlinx.coroutines.flow.MutableStateFlow +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 import androidx.compose.material.icons.filled.CheckCircle import androidx.compose.material.icons.filled.Error @@ -67,7 +75,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) @@ -81,6 +89,8 @@ fun DoctorScreen(controller: AppController, onBack: () -> Unit) { val context = LocalContext.current val service by controller.service.collectAsState() val servers by controller.servers.collectAsState() + // The speakers in the cast, as state: reading .value during composition would never update. + val active by (service?.activeDestinations ?: remember { MutableStateFlow(emptyList()) }).collectAsState() var checks by remember { mutableStateOf>(emptyList()) } var silentSince by remember { mutableStateOf(0L) } var lastSent by remember { mutableStateOf(-1L) } @@ -139,6 +149,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.notesFor(DeviceIdentity.of(d.platform, d.name, d.extra), java.util.Locale.getDefault()).forEach { (_, note) -> + list += Check(context.getString(R.string.doctor_known_behavior, d.name), CheckStatus.INFO, note) + } + } + // Data flowing? val stats = s.stats.value val flowing = stats.sentFrames > lastSent && lastSent >= 0 @@ -179,6 +196,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 +213,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)) @@ -203,6 +222,11 @@ fun DoctorScreen(controller: AppController, onBack: () -> Unit) { ListRow(stringResource(R.string.packet_exchange), leading = { LeadingIcon(Icons.AutoMirrored.Filled.ReceiptLong) }) { controller.openActivity(PacketLogActivity::class.java) } + active.filter { SpeakerFeedback.isAskable(it.platform) }.forEach { d -> + ListRow(stringResource(R.string.report_speaker_named, d.name), leading = { LeadingIcon(Icons.Filled.BugReport) }) { + 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 8c6b24e1..f82d0107 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,8 @@ 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 import androidx.compose.material.icons.filled.Delete @@ -112,6 +114,9 @@ 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.quirks.SpeakerFeedback +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 @@ -270,6 +275,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 +291,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 +309,11 @@ 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 = if (SpeakerFeedback.isAskable(server.platform)) { + { reportSpeaker(context, service, server.platform, server.name, server.host, server.extra) } + } else null, + onShareLog = { shareSpeakerLog(context, service, server.platform, server.name, server.host, server.extra) }) } } } @@ -313,7 +322,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)?, onShareLog: () -> Unit) { var menu by remember { mutableStateOf(false) } Box { ListRow( @@ -327,6 +336,11 @@ private fun SpeakerRow(server: Server, active: Boolean, onClick: () -> Unit, onR onClick = onClick, ) DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) { + // Software receivers (AriaCast, Snapcast, VBAN, Sendspin) are not speakers to report. + if (onReport != null) 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/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/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..377996bd --- /dev/null +++ b/app/src/main/java/com/aria/ariacast/ui/settings/KnownSpeakersScreen.kt @@ -0,0 +1,213 @@ +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.foundation.layout.size +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.KeyboardArrowDown +import androidx.compose.material.icons.filled.KeyboardArrowUp +import androidx.compose.material.icons.filled.Search +import androidx.compose.material.icons.filled.Speaker +import androidx.compose.material.icons.filled.Sync +import androidx.compose.material.icons.filled.Warning +import androidx.compose.material3.CircularProgressIndicator +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.collectAsState +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.Status +import com.aria.ariacast.scan.NetworkScanner +import com.aria.ariacast.scan.OtherDevice +import com.aria.ariacast.scan.ScanParsing +import com.aria.ariacast.ui.AppController +import com.aria.ariacast.ui.LeadingIcon +import com.aria.ariacast.ui.reportOtherDevice +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 is supported, what is supported with + * quirks, and what is not. It is kept in the AriaCast/known-speakers repository and downloaded + * from there (see [SpeakerListSync]). + */ +@Composable +fun KnownSpeakersScreen(controller: AppController, 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)) } + val servers by controller.servers.collectAsState() + var scanning by remember { mutableStateOf(false) } + var found by remember { mutableStateOf?>(null) } + + 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)) } + }, + ) + } + } + if (list.speakers.isEmpty()) item { + ListGroup { ListBlock { Text(stringResource(R.string.known_speakers_empty), style = MaterialTheme.typography.bodyMedium) } } + } + Status.entries.forEach { status -> + val rows = list.speakers.filter { it.status == status } + if (rows.isNotEmpty()) item(key = status.id) { + ListGroup(title = stringResource(statusLabel(status))) { rows.forEach { SpeakerEntryRow(it) } } + } + } + item { + ListGroup(Modifier.padding(top = 8.dp), title = stringResource(R.string.scan_title)) { + ListRow( + stringResource(R.string.scan_find), supporting = stringResource(R.string.scan_desc), + leading = { LeadingIcon(Icons.Filled.Search) }, + trailing = { if (scanning) CircularProgressIndicator(Modifier.size(24.dp), strokeWidth = 2.dp) }, + enabled = !scanning, + ) { + scanning = true + scope.launch { + // Speakers the app already lists are not "missing": leave them out. + found = NetworkScanner(context).scan(usableNames = servers.map { it.name }) + scanning = false + } + } + found?.let { devices -> + if (devices.isEmpty()) ListBlock { Text(stringResource(R.string.scan_none), style = MaterialTheme.typography.bodyMedium) } + devices.forEach { d -> + ListRow(d.name, supporting = ScanParsing.summary(d), leading = { LeadingIcon(Icons.Filled.Speaker) }) { reportOtherDevice(context, d) } + } + } + } + } + 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/known-speakers/issues/new?template=speaker-report.yml" + +private fun statusLabel(s: Status) = when (s) { + Status.SUPPORTED -> R.string.status_supported + Status.QUIRKS -> R.string.status_quirks + Status.UNSUPPORTED -> R.string.status_unsupported +} + +private fun statusIcon(s: Status): Pair = when (s) { + Status.SUPPORTED -> Icons.Filled.CheckCircle to StatusColors.Connected + Status.QUIRKS -> Icons.Filled.Warning to StatusColors.Warning + Status.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) = statusIcon(k.status) + ListRow( + headline = k.speaker, + supporting = k.protocol, + leading = { Icon(icon, null, tint = tint, 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) } + if (k.reports.isNotEmpty()) Detail(stringResource(R.string.known_speakers_reports), reportsText(k)) + Detail(stringResource(R.string.known_speakers_evidence), plain(k.evidence)) + if (k.locked) Text(stringResource(R.string.known_speakers_locked), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + } +} + +@Composable +private fun reportsText(k: KnownSpeaker): String { + // The labels are read first: a composable cannot be called from inside joinToString's lambda. + val labels = Status.entries.associateWith { stringResource(statusLabel(it)).lowercase() } + return Status.entries.filter { (k.reports[it] ?: 0) > 0 }.joinToString(", ") { "${k.reports[it]} ${labels[it]}" } +} + +@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 5569ea81..774d7da5 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,65 @@ Inviati %1$d ยท ricevuti %2$d ยท persi %3$d Firmware %1$s, %2$d interruzioni. Copia il report + %1$s: comportamento noto + Segnala altoparlante + Segnala %1$s + Segnalazione AriaCast: %1$s + Log copiato. Incollalo nel campo ยซLogยป della segnalazione. + Condividi il log + Come va con %1$s? + Trasmetti a %1$s da un minuto. Funziona? + Funziona + C\'รจ un problema + Cosa non va? + Suona, ma qualcosa non va + Non funziona + Cosa succede? + Continua + Annulla + Aggiungerlo alla lista? + %1$s non รจ ancora tra gli altoparlanti supportati. Puoi aggiungerlo alla lista pubblica su GitHub (serve un account). Il tuo log resta tuo. + Aggiungi + No, grazie + Grazie! + Feedback sugli altoparlanti + Tocca per dirci se funziona. + Non riesco a collegarmi a %1$s + La trasmissione verso %1$s non รจ riuscita. Segnalarlo aiuta a capire cosa non va con questo altoparlante. + Segnala + Tocca per segnalarlo. + Altoparlanti noti + Quali altoparlanti sono supportati, quali hanno limiti e quali no. + 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 + Supportato + Supportato con limiti + Non supportato + Segnalazioni + Un manutentore ha verificato questa voce; le nuove segnalazioni vengono contate ma non la cambiano. + Nessun elenco per ora. Si scarica la prima volta che sei online; tocca ยซAggiorna oraยป per averlo. + Altri dispositivi nella tua rete + Cerca altri dispositivi + Cerca dispositivi su cui AriaCast non puรฒ riprodurre (Spotify Connect, Alexa, HomeKit e simili) per poterli aggiungere alla lista. Richiede circa 8 secondi. Tocca un risultato per segnalarlo. + Non รจ stato trovato altro. Alcuni dispositivi rispondono solo da svegli. + AriaCast si รจ fermata all\'improvviso + Condividi il rapporto + Chiudi + Nessun rapporto salvato. 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..d25b701b 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,65 @@ Sent %1$d ยท received %2$d ยท dropped %3$d Firmware %1$s, %2$d dropouts. Copy report + %1$s: known behavior + Report speaker + Report %1$s + AriaCast report: %1$s + Log copied. Paste it in the โ€œLogโ€ field of the report. + Share log + How is %1$s working? + You have been casting to %1$s for a minute. Does it work? + It works + There\'s a problem + What is wrong? + It plays, but something is wrong + It doesn\'t work + What happens? + Continue + Cancel + Add it to the list? + %1$s is not listed as supported yet. You can add it to the public list on GitHub (an account is needed). Your log stays yours. + Add + No thanks + Thanks! + Speaker feedback + Tap to tell us if it works. + Couldn\'t connect to %1$s + Casting to %1$s failed. Reporting it helps work out what is wrong with this speaker. + Report + Tap to report it. + Known speakers + Which speakers are supported, which have quirks, and which are not. + 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 + Supported + Supported with quirks + Unsupported + Reports + A maintainer checked this entry; new reports are counted but do not change it. + No list yet. The list is downloaded the first time you are online; tap โ€œUpdate nowโ€ to get it. + Other devices on your network + Look for other devices + Looks for devices AriaCast can\'t play to (Spotify Connect, Alexa, HomeKit and the like) so you can add them to the list. Takes about 8 seconds. Tap a result to report it. + Nothing else found. Some devices only answer when they are awake. + AriaCast stopped unexpectedly + Share the report + Close + No report was kept. 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/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 b9591fd2..75a6b954 100644 --- a/app/src/test/java/com/aria/ariacast/PacketLoggerTest.kt +++ b/app/src/test/java/com/aria/ariacast/PacketLoggerTest.kt @@ -81,4 +81,67 @@ 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) + } + + 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/StartupSmokeTest.kt b/app/src/test/java/com/aria/ariacast/StartupSmokeTest.kt new file mode 100644 index 00000000..b1432b98 --- /dev/null +++ b/app/src/test/java/com/aria/ariacast/StartupSmokeTest.kt @@ -0,0 +1,86 @@ +package com.aria.ariacast + +import android.app.Application +import android.content.ComponentName +import android.content.Context +import android.content.Intent +import android.os.Looper +import androidx.test.core.app.ActivityScenario +import androidx.test.core.app.ApplicationProvider +import java.time.Duration +import java.util.Collections +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config + +/** + * Starts the real app on the JVM, as a user who finished the setup, and fails if anything crashes: + * the main thread or any background thread. Unit tests of the parts cannot see a crash that only + * happens when the parts run together. + */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [29, 34]) // Android 15 and later need Java 21 in Robolectric; the CI runs Java 17 +class StartupSmokeTest { + private val crashes = Collections.synchronizedList(mutableListOf()) + private var previous: Thread.UncaughtExceptionHandler? = null + + @Before fun catchCrashes() { + org.robolectric.shadows.ShadowLog.stream = System.out + previous = Thread.getDefaultUncaughtExceptionHandler() + Thread.setDefaultUncaughtExceptionHandler { _, e -> crashes += e } + } + + @After fun restore() = Thread.setDefaultUncaughtExceptionHandler(previous) + + private fun idle() = repeat(10) { + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(500)) + Thread.sleep(100) // let background work (the list download, discovery) run too + } + + private fun bindRealService(context: Context) { + // Robolectric binds services with no component name unless told which one answers; a + // phone always passes it. Give it the real service, created the way Android would. + val service = Robolectric.buildService(AudioCastService::class.java).create().get() + shadowOf(context as Application).setComponentNameAndServiceForBindService( + ComponentName(context, AudioCastService::class.java), service.onBind(Intent()), + ) + } + + private fun assertNoCrash() = + assertEquals(crashes.joinToString("\n\n") { it.stackTraceToString().take(4000) }, 0, crashes.size) + + @Test fun afterTheSetupTheHomeScreenComesUpWithoutCrashing() { + val context = ApplicationProvider.getApplicationContext() + context.getSharedPreferences(AudioCastService.PREFS_NAME, Context.MODE_PRIVATE).edit() + .putBoolean(MainActivity.KEY_ONBOARDED, true).commit() + bindRealService(context) + ActivityScenario.launch(MainActivity::class.java).use { scenario -> + idle() + scenario.onActivity { } + } + assertNoCrash() + } + + @Test fun finishingTheSetupWithSpeakersOnTheNetworkDoesNotCrash() { + val context = ApplicationProvider.getApplicationContext() + bindRealService(context) + ActivityScenario.launch(MainActivity::class.java).use { scenario -> + idle() + scenario.onActivity { it.finishOnboarding() } + idle() + // One speaker per protocol, as discovery would list them, so every row is drawn. + scenario.onActivity { a -> + listOf("AirPlay", "AirPlay2", "DLNA", "Google Cast", "AriaCast", "Snapcast", "VBAN", "Sendspin", "Manual") + .forEachIndexed { i, p -> a.addManualServer("192.168.1.${10 + i}", 7000 + i, "Speaker $p", p, "model=WiiM Pro;manufacturer=Linkplay") } + } + idle() + } + assertNoCrash() + } +} diff --git a/app/src/test/java/com/aria/ariacast/crash/CrashReportTest.kt b/app/src/test/java/com/aria/ariacast/crash/CrashReportTest.kt new file mode 100644 index 00000000..f0e2a79f --- /dev/null +++ b/app/src/test/java/com/aria/ariacast/crash/CrashReportTest.kt @@ -0,0 +1,37 @@ +package com.aria.ariacast.crash + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class CrashReportTest { + private fun report(error: Throwable, thread: String = "main") = + CrashReport.format(error, thread, "com.aria.ariacast.test 2.0.0-test", "Google Pixel 8, Android 14 (API 34)", "2026-11-27 11:40:00") + + @Test fun itSaysWhatCrashedAndWhere() { + val text = report(IllegalStateException("no service"), thread = "DefaultDispatcher-worker-3") + assertTrue(text.startsWith("AriaCast crash report")) + assertTrue(text.contains("Thread: DefaultDispatcher-worker-3")) + assertTrue(text.contains("App: com.aria.ariacast.test 2.0.0-test")) + assertTrue(text.contains("Device: Google Pixel 8, Android 14 (API 34)")) + assertTrue(text.contains("java.lang.IllegalStateException: no service")) + assertTrue(text.contains("at com.aria.ariacast.crash.CrashReportTest")) + } + + @Test fun theCauseIsKept() { + val text = report(RuntimeException("outer", IllegalArgumentException("the real reason"))) + assertTrue(text.contains("Caused by: java.lang.IllegalArgumentException: the real reason")) + } + + @Test fun anErrorWithoutAMessageStillReports() { + assertTrue(report(NullPointerException()).contains("java.lang.NullPointerException")) + } + + @Test fun aHugeTraceIsCutButKeepsItsTop() { + fun deep(n: Int): Nothing = if (n == 0) throw StackOverflowError("deep") else deep(n - 1) + val error = try { deep(5000) } catch (e: StackOverflowError) { e } + val text = report(error) + assertEquals(CrashReport.MAX_CHARS + "\n... (cut)".length, text.length) + assertTrue(text.contains("java.lang.StackOverflowError: deep")) + } +} 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..a4503307 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)!! @@ -76,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("")) + } } 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..e154a627 --- /dev/null +++ b/app/src/test/java/com/aria/ariacast/quirks/DeviceQuirksTest.kt @@ -0,0 +1,97 @@ +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() { + 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 matchesShairportPerAirPlayVersion() { + assertEquals(listOf("shairport-airplay2-ptp"), ids(DeviceIdentity("AirPlay2", "Kitchen", "ShairportSync"))) + 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 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", Status.SUPPORTED, 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(Status.UNSUPPORTED, DeviceQuirks.matching(DeviceIdentity(null, "Echo Show 5 kitchen")).single().status) + } + + @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/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..567726b9 --- /dev/null +++ b/app/src/test/java/com/aria/ariacast/quirks/KnownSpeakersFileTest.kt @@ -0,0 +1,165 @@ +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.assertTrue +import org.junit.Test + +class KnownSpeakersFileTest { + private fun entry( + id: String = "wiim-dlna", + status: String = "supported", + mentions: String = """["wiim"]""", + evidence: String = "an issue", + extra: String = "", + ) = """{"id":"$id","speaker":"WiiM","protocol":"DLNA","status":"$status","match":{"platform":"DLNA","mentions":$mentions},"evidence":"$evidence"$extra}""" + + private fun file(vararg entries: String, schema: Int = 2, 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(Status.SUPPORTED, list.speakers.single().status) + assertTrue(list.skipped.isEmpty()) + } + + @Test fun refusesWholeFilesThatCannotBeTrusted() { + assertNull(KnownSpeakersFile.parse("not json")) + assertNull(KnownSpeakersFile.parse(file(entry(), schema = 3))) + 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-status", status = "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-status: unknown status", "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":2,"version":1,"speakers":[{"id":"any-proto","speaker":"S","protocol":"p","status":"unsupported","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":2,"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 reportsAndTheLockAreReadAndBadCountsAreDropped() { + val k = KnownSpeakersFile.parse( + file(entry(extra = ""","reports":{"supported":3,"quirks":1,"unsupported":-2,"great":9,"quirks2":1},"locked":true""")) + )!!.speakers.single() + assertEquals(mapOf(Status.SUPPORTED to 3, Status.QUIRKS to 1), k.reports) + assertTrue(k.locked) + val plain = KnownSpeakersFile.parse(file(entry()))!!.speakers.single() + assertEquals(emptyMap(), plain.reports) + assertFalse(plain.locked) + } + + @Test fun anAbsurdReportCountIsDropped() { + val k = KnownSpeakersFile.parse(file(entry(extra = ""","reports":{"supported":99999999}""")))!!.speakers.single() + assertEquals(emptyMap(), k.reports) + } + + @Test fun aFileOfTheOldSchemaIsRefused() { + assertNull(KnownSpeakersFile.parse(file(entry(), schema = 1))) + } + + @Test fun whatTheBotProposesIsAcceptedByTheApp() { + // bot-output.json is what the known-speakers bot writes for its sample report (that + // repository's tests check the bot still produces exactly this file). + val list = KnownSpeakersFile.parse(TestSpeakers.text("bot-output.json"))!! + assertEquals(emptyList(), list.skipped) + assertEquals(listOf("wiim-dlna-restart", "open-box-dlna", "acme-play-3-dlna"), list.speakers.map { it.id }) + val acme = list.speakers.last() + assertEquals(Status.QUIRKS, acme.status) + assertEquals(mapOf(Status.QUIRKS to 1), acme.reports) + assertFalse(acme.locked) + assertTrue(acme.appliesTo(DeviceIdentity("DLNA", "Den", "Play 3 Pro", "Acme Audio"))) + assertFalse(acme.appliesTo(DeviceIdentity("AirPlay2", "Den", "Play 3 Pro"))) + assertTrue(list.speakers.first().locked) + } + + @Test fun theShippedSnapshotOfTheListHasNoRejectedEntries() { + assertEquals(emptyList(), TestSpeakers.load().skipped) + } +} diff --git a/app/src/test/java/com/aria/ariacast/quirks/MatchingCasesTest.kt b/app/src/test/java/com/aria/ariacast/quirks/MatchingCasesTest.kt new file mode 100644 index 00000000..81d5b3a5 --- /dev/null +++ b/app/src/test/java/com/aria/ariacast/quirks/MatchingCasesTest.kt @@ -0,0 +1,42 @@ +package com.aria.ariacast.quirks + +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.contentOrNull +import kotlinx.serialization.json.jsonArray +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The cases the known-speakers bot also runs (resources/matching-cases.json is the same file as + * known-speakers/tests/data/matching-cases.json). The app and the bot decide which entry a device + * belongs to separately; this is what keeps the two from disagreeing. + */ +class MatchingCasesTest { + private val root = Json.parseToJsonElement(TestSpeakers.text("matching-cases.json")).jsonObject + + private fun device(o: JsonObject) = DeviceIdentity( + platform = o["platform"]?.jsonPrimitive?.contentOrNull, + name = o["name"]?.jsonPrimitive?.contentOrNull.orEmpty(), + model = o["model"]?.jsonPrimitive?.contentOrNull, + manufacturer = o["manufacturer"]?.jsonPrimitive?.contentOrNull, + ) + + @Test fun theAppAnswersEveryCaseLikeTheBot() { + val list = KnownSpeakersFile.parse(root.getValue("list").toString())!! + assertEquals(emptyList(), list.skipped) + KnownSpeakersStore.setForTesting(list) + val cases = root.getValue("cases").jsonArray + assertTrue(cases.size >= 10) + for (c in cases) { + val o = c.jsonObject + val why = o.getValue("why").jsonPrimitive.content + val d = device(o.getValue("device").jsonObject) + assertEquals(why, o.getValue("matches").jsonArray.map { it.jsonPrimitive.content }, DeviceQuirks.matching(d).map { it.id }) + assertEquals(why, o["best"]?.jsonPrimitive?.contentOrNull, DeviceQuirks.bestMatch(d)?.id) + } + } +} diff --git a/app/src/test/java/com/aria/ariacast/quirks/SpeakerFeedbackTest.kt b/app/src/test/java/com/aria/ariacast/quirks/SpeakerFeedbackTest.kt new file mode 100644 index 00000000..ef34e2d6 --- /dev/null +++ b/app/src/test/java/com/aria/ariacast/quirks/SpeakerFeedbackTest.kt @@ -0,0 +1,79 @@ +package com.aria.ariacast.quirks + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +class SpeakerFeedbackTest { + @Before fun loadTheList() { TestSpeakers.load() } + + @Test fun aSpeakerIsToldApartByProtocolAndName() { + assertEquals("DLNA|den", SpeakerFeedback.key("DLNA", " Den ")) + assertEquals(SpeakerFeedback.key("DLNA", "DEN"), SpeakerFeedback.key("DLNA", "den")) + assertFalse(SpeakerFeedback.key("DLNA", "Den") == SpeakerFeedback.key("AirPlay2", "Den")) + assertEquals("-|den", SpeakerFeedback.key(null, "Den")) + } + + @Test fun itAsksOnlyWhenAllIsInPlace() { + assertTrue(SpeakerFeedback.shouldAsk(casting = true, stillInCast = true, alreadyAsked = false, platform = "DLNA")) + assertFalse(SpeakerFeedback.shouldAsk(casting = false, stillInCast = true, alreadyAsked = false, platform = "DLNA")) + assertFalse("removed from the cast meanwhile", SpeakerFeedback.shouldAsk(true, false, false, "DLNA")) + assertFalse("never twice", SpeakerFeedback.shouldAsk(true, true, true, "DLNA")) + // Software on a phone, a computer or a server is not a speaker to judge. + listOf("Sendspin", "AriaCast", "Snapcast", "VBAN", null).forEach { + assertFalse("$it", SpeakerFeedback.shouldAsk(true, true, false, it)) + } + listOf("AirPlay", "AirPlay2", "DLNA", "Google Cast").forEach { + assertTrue("$it", SpeakerFeedback.shouldAsk(true, true, false, it)) + } + } + + @Test fun aFailureIsAskedAboutOnlyForASingleSpeaker() { + assertTrue(SpeakerFeedback.shouldAskAfterFailure(1, alreadyAsked = false, platform = "DLNA")) + assertFalse("which of two failed?", SpeakerFeedback.shouldAskAfterFailure(2, false, "DLNA")) + assertFalse("never twice", SpeakerFeedback.shouldAskAfterFailure(1, true, "DLNA")) + assertFalse(SpeakerFeedback.shouldAskAfterFailure(1, false, "Sendspin")) + assertFalse(SpeakerFeedback.shouldAskAfterFailure(1, false, "VBAN")) + assertFalse(SpeakerFeedback.shouldAskAfterFailure(0, false, "DLNA")) + } + + @Test fun aMinuteIsTheWait() { + assertEquals(60_000L, SpeakerFeedback.ASK_AFTER_MS) + } + + @Test fun sharingIsOfferedUnlessTheListAlreadySaysSupported() { + fun best(platform: String, name: String, model: String?) = DeviceQuirks.bestMatch(DeviceIdentity(platform, name, model)) + assertTrue("not in the list", SpeakerFeedback.offerSharingAfterWorks(best("DLNA", "Den", "Acme Box"))) + assertFalse("listed as supported", SpeakerFeedback.offerSharingAfterWorks(best("DLNA", "Den", "WiiM Pro Plus"))) + assertTrue("listed with quirks: a confirmation is news", SpeakerFeedback.offerSharingAfterWorks(best("AirPlay2", "Den", "ShairportSync"))) + } + + @Test fun answersMapToTheFormsWords() { + assertEquals("Supported", SpeakerFeedback.formLabel(Status.SUPPORTED)) + assertEquals("Supported with quirks", SpeakerFeedback.formLabel(Status.QUIRKS)) + assertEquals("Unsupported", SpeakerFeedback.formLabel(Status.UNSUPPORTED)) + val form = TestSpeakers.text("speaker-report-form.yml") + Status.entries.forEach { assertTrue(form.contains("- ${SpeakerFeedback.formLabel(it)}\n")) } + } + + private fun ledger(store: MutableMap = mutableMapOf()) = FeedbackLedger({ store[it] }, { k, v -> store[k] = v }) + + @Test fun theLedgerRemembersWhatWasAskedAndAnswered() { + val store = mutableMapOf() + val l = ledger(store) + assertFalse(l.asked("DLNA|den")) + assertNull(l.answer("DLNA|den")) + l.markAsked("DLNA|den", 123L) + l.record("DLNA|den", Status.QUIRKS) + assertTrue(ledger(store).asked("DLNA|den")) // a new ledger over the same storage: it persists + assertEquals(Status.QUIRKS, ledger(store).answer("DLNA|den")) + assertFalse(ledger(store).asked("DLNA|other")) + } + + @Test fun anAnswerFromAnOlderOrDamagedStoreIsIgnored() { + assertNull(ledger(mutableMapOf("answer.x" to "great")).answer("x")) + } +} 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..fa4a16f1 --- /dev/null +++ b/app/src/test/java/com/aria/ariacast/quirks/SpeakerIssueTest.kt @@ -0,0 +1,96 @@ +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/known-speakers/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["details"]) + assertEquals("2.0.0", q["version"]) + } + + @Test fun theStatusIsOnlySetWhenKnown() { + assertNull(query(SpeakerIssue.url(wiim, "d", null))["status"]) + assertEquals("Unsupported", query(SpeakerIssue.url(wiim, "d", null, SpeakerIssue.STATUS_UNSUPPORTED))["status"]) + } + + @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() { + // A copy of the known-speakers repository's form: keep it in step with that file. + val form = TestSpeakers.text("speaker-report-form.yml") + listOf("AirPlay2", "AirPlay", "DLNA", "Google Cast", null, "x").forEach { + assertTrue("${SpeakerIssue.protocolLabel(it)} is not an option in the form", form.contains("- ${SpeakerIssue.protocolLabel(it)}\n")) + } + listOf(SpeakerIssue.STATUS_SUPPORTED, SpeakerIssue.STATUS_QUIRKS, SpeakerIssue.STATUS_UNSUPPORTED).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", "Mod&el=1#") + val q = query(SpeakerIssue.url(nasty, "line one\nline two & more = # ?", null)) + assertEquals("Mod&el=1#", q["speaker"]) + assertEquals("line one\nline two & more = # ?", q["details"]) + 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)["details"]!!.isNotEmpty()) + } + + @Test fun aSpeakerThatSaysNothingAboutItselfIsLeftForTheReporterToName() { + // "Kitchen" is what its owner called it, not what it is: the form must ask for the model. + assertEquals("", SpeakerIssue.speakerName(DeviceIdentity("AirPlay2", "Kitchen"))) + val q = query(SpeakerIssue.url(DeviceIdentity("AirPlay2", "Kitchen"), "d", null)) + assertNull(q["speaker"]) + assertNull(q["title"]) + assertEquals("AirPlay 2", q["protocol"]) + } + + @Test fun softwareReceiversAreNotOffered() { + listOf("AriaCast", "Snapcast", "VBAN", "Sendspin").forEach { assertEquals("Other", SpeakerIssue.protocolLabel(it)) } + } + + @Test fun whatTheUserWroteGoesInTheSymptomsField() { + val q = query(SpeakerIssue.url(wiim, "d", null, SpeakerIssue.STATUS_QUIRKS, " Stops after one track\nneeds a manual play ")) + assertEquals("Stops after one track\nneeds a manual play", q["symptoms"]) + assertEquals("Supported with quirks", q["status"]) + } + + @Test fun anEmptyOrOversizedNoteIsHandled() { + assertNull(query(SpeakerIssue.url(wiim, "d", null, null, " "))["symptoms"]) + assertEquals(SpeakerIssue.MAX_SYMPTOMS, query(SpeakerIssue.url(wiim, "d", null, null, "z".repeat(5000)))["symptoms"]!!.length) + } + + @Test fun theSymptomsStayWhenTheDetailsAreCut() { + val url = SpeakerIssue.url(wiim, "y".repeat(50_000), null, null, "It stops") + assertTrue(url.length <= SpeakerIssue.MAX_URL) + assertEquals("It stops", query(url)["symptoms"]) + } +} 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..d5336fec --- /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":2}""")) + assertEquals("""{"schema":2}""", 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":2,"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 new file mode 100644 index 00000000..c6b251f7 --- /dev/null +++ b/app/src/test/java/com/aria/ariacast/quirks/SpeakerReportTest.kt @@ -0,0 +1,88 @@ +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.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) + + // 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: Supported")) + 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")) + } + + @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/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..b3db8907 --- /dev/null +++ b/app/src/test/java/com/aria/ariacast/quirks/TestSpeakers.kt @@ -0,0 +1,17 @@ +package com.aria.ariacast.quirks + +/** + * A copy of the real list (AriaCast/known-speakers), read from the test resources and put in use + * for a test. It is a snapshot: refresh src/test/resources/speakers.json when the list gains + * entries a test relies on. + */ +object TestSpeakers { + fun text(name: String): String = + TestSpeakers::class.java.getResource("/$name")?.readText() ?: error("missing test resource $name") + + fun load(): KnownSpeakersFile { + val parsed = KnownSpeakersFile.parse(text("speakers.json")) ?: error("speakers.json does not parse") + KnownSpeakersStore.setForTesting(parsed) + return parsed + } +} diff --git a/app/src/test/java/com/aria/ariacast/scan/ScanParsingTest.kt b/app/src/test/java/com/aria/ariacast/scan/ScanParsingTest.kt new file mode 100644 index 00000000..16db7dba --- /dev/null +++ b/app/src/test/java/com/aria/ariacast/scan/ScanParsingTest.kt @@ -0,0 +1,110 @@ +package com.aria.ariacast.scan + +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 +import com.aria.ariacast.quirks.SpeakerIssue + +class ScanParsingTest { + private fun description(name: String = "Echo Show 5", extra: String = "", services: List = emptyList()) = + """urn:schemas-upnp-org:device:Basic:1 +$nameAmazonEcho Show 5$extra +${services.joinToString("") { "$it" }}""" + + @Test fun anSsdpAnswerIsReadWhateverTheCaseOfItsHeaders() { + val reply = ScanParsing.ssdpReply("HTTP/1.1 200 OK\r\nCache-Control: max-age=1800\r\nlocation: http://192.168.1.9:8008/desc.xml\r\nSERVER: Linux/3.14 UPnP/1.0\r\nST: ssdp:all\r\n\r\n")!! + assertEquals("http://192.168.1.9:8008/desc.xml", reply.location) + assertEquals("Linux/3.14 UPnP/1.0", reply.server) + } + + @Test fun anAnswerThatDoesNotSayWhereTheDeviceIsIsIgnored() { + assertNull(ScanParsing.ssdpReply("HTTP/1.1 200 OK\r\nST: ssdp:all\r\n\r\n")) + assertNull(ScanParsing.ssdpReply("")) + assertNull(ScanParsing.ssdpReply("LOCATION:\r\n")) + } + + @Test fun aDescriptionGivesTheDevice() { + val d = ScanParsing.description(description(services = listOf("urn:schemas-upnp-org:service:RenderingControl:1")), "192.168.1.9", "Linux")!! + assertEquals("Echo Show 5", d.friendlyName) + assertEquals("Amazon", d.manufacturer) + assertEquals("Echo Show 5", d.modelName) + assertEquals(listOf("urn:schemas-upnp-org:service:RenderingControl:1"), d.services) + assertEquals("192.168.1.9", d.host) + } + + @Test fun aDescriptionWithoutANameOrTooBigIsNotADevice() { + assertNull(ScanParsing.description("", "h", null)) + assertNull(ScanParsing.description(description(extra = "x".repeat(ScanParsing.MAX_DESCRIPTION_BYTES)), "h", null)) + } + + @Test fun textFromTheDeviceIsUnescapedCleanedAndCapped() { + val d = ScanParsing.description(description(name = "Kitchen & Den\u0007" + "x".repeat(300)), "h", null)!! + assertTrue(d.friendlyName.startsWith("Kitchen & Den")) + assertTrue(d.friendlyName.none { it < ' ' }) + assertEquals(80, d.friendlyName.length) + } + + @Test fun aRendererIsSomethingAriaCastAlreadyPlaysTo() { + val renderer = ScanParsing.description(description(services = listOf("urn:schemas-upnp-org:service:AVTransport:1")), "h", null)!! + assertTrue(renderer.isRenderer) + assertTrue(ScanParsing.otherDevices(listOf(renderer), emptyList()).isEmpty()) + } + + @Test fun mdnsServicesAreGroupedByNameAndTheirTypesSorted() { + val found = ScanParsing.otherDevices( + emptyList(), + listOf(MdnsFound("Echo Show 5-3f2", "_spotify-connect._tcp"), MdnsFound("Echo Show 5-3f2", "_amzn-wplay._tcp"), MdnsFound("Echo Show 5-3f2", "_amzn-wplay._tcp"), MdnsFound("Kitchen Hub", "_hap._tcp")), + ) + assertEquals(listOf("Echo Show 5-3f2", "Kitchen Hub"), found.map { it.name }) + assertEquals(listOf("_amzn-wplay._tcp", "_spotify-connect._tcp"), found.first().mdnsTypes) + } + + @Test fun aDeviceSeenByBothWaysIsOneDevice() { + val ssdp = ScanParsing.description(description(name = "Echo Show 5-3f2"), "192.168.1.9", "Linux")!! + val found = ScanParsing.otherDevices(listOf(ssdp), listOf(MdnsFound("Echo Show 5-3f2", "_spotify-connect._tcp"))) + assertEquals(1, found.size) + assertEquals("Amazon", found.single().manufacturer) + assertEquals(listOf("_spotify-connect._tcp"), found.single().mdnsTypes) + assertEquals("192.168.1.9", found.single().host) + } + + @Test fun speakersTheAppAlreadyListsAreLeftOut() { + val found = ScanParsing.otherDevices( + emptyList(), + listOf(MdnsFound("Living Room", "_sonos._tcp"), MdnsFound("Echo Show 5-3f2", "_amzn-wplay._tcp")), + usableNames = listOf("living room", ""), + ) + assertEquals(listOf("Echo Show 5-3f2"), found.map { it.name }) + } + + @Test fun aNameLessServiceIsIgnored() { + assertTrue(ScanParsing.otherDevices(emptyList(), listOf(MdnsFound(" ", "_hap._tcp"))).isEmpty()) + } + + @Test fun theFingerprintSaysWhatWasFoundAndShortensAddresses() { + val d = OtherDevice("Echo Show 5-3f2", "Amazon", "Echo Show 5", listOf("_amzn-wplay._tcp"), "urn:x:device:Basic:1", listOf("urn:x:service:Foo:1"), "Linux", "192.168.1.9") + val text = ScanParsing.fingerprint(d) + assertTrue(text.contains("Name: Echo Show 5-3f2")) + assertTrue(text.contains("mDNS: _amzn-wplay._tcp")) + assertTrue(text.contains("UPnP services: urn:x:service:Foo:1")) + assertTrue(text.contains("Address: 192.168.x.x")) + assertFalse(text.contains("192.168.1.9")) + } + + @Test fun theListShowsWhatKindOfThingItAnnounced() { + assertEquals("Spotify Connect, Amazon ยท Amazon Echo Show 5", ScanParsing.summary(OtherDevice("n", "Amazon", "Echo Show 5", listOf("_spotify-connect._tcp", "_amzn-wplay._tcp")))) + assertEquals("UPnP", ScanParsing.summary(OtherDevice("n"))) + } + + @Test fun aFoundDeviceBecomesAReportWithNoProtocol() { + val d = OtherDevice("Echo Show 5-3f2", "Amazon", "Echo Show 5") + val url = SpeakerIssue.url(ScanParsing.identity(d), ScanParsing.fingerprint(d), "2.0.0", symptoms = "AriaCast does not find it as a speaker.") + val q = url.substringAfter('?').split('&').associate { it.substringBefore('=') to URLDecoder.decode(it.substringAfter('='), "UTF-8") } + assertEquals("Amazon Echo Show 5", q["speaker"]) + assertEquals("No local protocol", q["protocol"]) + assertNull(q["status"]) + } +} diff --git a/app/src/test/resources/bot-output.json b/app/src/test/resources/bot-output.json new file mode 100644 index 00000000..f2061942 --- /dev/null +++ b/app/src/test/resources/bot-output.json @@ -0,0 +1,58 @@ +{ + "schema": 2, + "version": 5, + "updated": "2026-11-27", + "speakers": [ + { + "id": "wiim-dlna-restart", + "speaker": "WiiM (tested on Pro Plus)", + "protocol": "DLNA", + "status": "supported", + "match": { + "platform": "DLNA", + "mentions": [ + "wiim" + ] + }, + "evidence": "[#50](https://github.com/AriaCast/AriaCast-app/issues/50)", + "locked": true, + "reports": {} + }, + { + "id": "open-box-dlna", + "speaker": "Open Box", + "protocol": "DLNA", + "status": "supported", + "match": { + "platform": "DLNA", + "mentions": [ + "open box" + ] + }, + "evidence": "[#9](https://github.com/AriaCast/known-speakers/issues/9), reported by a user", + "reports": { + "supported": 1 + } + }, + { + "id": "acme-play-3-dlna", + "speaker": "Acme Play 3", + "protocol": "DLNA", + "status": "quirks", + "match": { + "platform": "DLNA", + "mentions": [ + "play 3 pro" + ] + }, + "symptoms": [ + "Stops after the first track", + "Needs a manual play in the Acme app" + ], + "evidence": "[#77](https://github.com/AriaCast/known-speakers/issues/77), reported by a user", + "reports": { + "quirks": 1 + } + } + ] +} diff --git a/app/src/test/resources/matching-cases.json b/app/src/test/resources/matching-cases.json new file mode 100644 index 00000000..b09c6806 --- /dev/null +++ b/app/src/test/resources/matching-cases.json @@ -0,0 +1,255 @@ +{ + "comment": "Shared by the apps and the bot: the same list and the same answers. Keep this file identical in AriaCast/known-speakers (tests/data) and AriaCast-app (app/src/test/resources).", + "list": { + "schema": 2, + "version": 1, + "updated": "2026-11-27", + "speakers": [ + { + "id": "wiim", + "speaker": "wiim", + "protocol": "DLNA", + "status": "supported", + "match": { + "mentions": [ + "wiim", + "linkplay" + ], + "platform": "DLNA" + }, + "evidence": "e" + }, + { + "id": "wiim-pro", + "speaker": "wiim-pro", + "protocol": "DLNA", + "status": "supported", + "match": { + "mentions": [ + "wiim pro" + ], + "platform": "DLNA" + }, + "evidence": "e" + }, + { + "id": "sonos-airplay2", + "speaker": "sonos-airplay2", + "protocol": "AirPlay2", + "status": "supported", + "match": { + "mentions": [ + "sonos" + ], + "platform": "AirPlay2" + }, + "evidence": "e" + }, + { + "id": "sonos-dlna", + "speaker": "sonos-dlna", + "protocol": "DLNA", + "status": "supported", + "match": { + "mentions": [ + "sonos" + ], + "platform": "DLNA" + }, + "evidence": "e" + }, + { + "id": "echo", + "speaker": "echo", + "protocol": "No local protocol", + "status": "unsupported", + "match": { + "mentions": [ + "echo show 5", + "echo hub" + ] + }, + "evidence": "e", + "symptoms": [ + "not found" + ] + }, + { + "id": "appletv", + "speaker": "appletv", + "protocol": "No local protocol", + "status": "supported", + "match": { + "mentions": [ + "appletv" + ] + }, + "evidence": "e" + }, + { + "id": "shairport", + "speaker": "shairport", + "protocol": "AirPlay", + "status": "supported", + "match": { + "mentions": [ + "shairport" + ], + "platform": "AirPlay" + }, + "evidence": "e" + } + ] + }, + "cases": [ + { + "why": "a WiiM Pro Plus matches both WiiM entries, the more specific one is best", + "device": { + "platform": "DLNA", + "name": "Den", + "model": "WiiM Pro Plus", + "manufacturer": "Linkplay" + }, + "matches": [ + "wiim", + "wiim-pro" + ], + "best": "wiim-pro" + }, + { + "why": "a WiiM Mini only the general one", + "device": { + "platform": "DLNA", + "name": "WiiM Mini-1234", + "model": "WiiM Mini" + }, + "matches": [ + "wiim" + ], + "best": "wiim" + }, + { + "why": "the maker alone is enough", + "device": { + "platform": "DLNA", + "name": "Den", + "manufacturer": "Linkplay Technology Inc." + }, + "matches": [ + "wiim" + ], + "best": "wiim" + }, + { + "why": "the protocol must match when the entry has one", + "device": { + "platform": "AirPlay2", + "name": "WiiM Pro Plus" + }, + "matches": [], + "best": null + }, + { + "why": "Sonos over AirPlay 2", + "device": { + "platform": "AirPlay2", + "name": "Living", + "model": "Sonos Era 100" + }, + "matches": [ + "sonos-airplay2" + ], + "best": "sonos-airplay2" + }, + { + "why": "Sonos over DLNA", + "device": { + "platform": "DLNA", + "name": "Living", + "model": "Play:5", + "manufacturer": "Sonos, Inc." + }, + "matches": [ + "sonos-dlna" + ], + "best": "sonos-dlna" + }, + { + "why": "matching ignores case", + "device": { + "platform": "DLNA", + "name": "Living", + "model": "SONOS PLAY:5" + }, + "matches": [ + "sonos-dlna" + ], + "best": "sonos-dlna" + }, + { + "why": "an entry without a protocol matches whatever the device speaks", + "device": { + "platform": "AirPlay2", + "name": "Studio", + "model": "AppleTV11,1" + }, + "matches": [ + "appletv" + ], + "best": "appletv" + }, + { + "why": "a device with no protocol, found by a scan, matches an entry with none", + "device": { + "platform": null, + "name": "Echo Show 5-3f2" + }, + "matches": [ + "echo" + ], + "best": "echo" + }, + { + "why": "typed brand and model count as the model", + "device": { + "platform": null, + "model": "Amazon Echo Show 5" + }, + "matches": [ + "echo" + ], + "best": "echo" + }, + { + "why": "a device with no protocol does not match an entry that names one", + "device": { + "platform": null, + "name": "Den", + "model": "WiiM Pro Plus" + }, + "matches": [], + "best": null + }, + { + "why": "a name is enough when nothing else is known", + "device": { + "platform": "AirPlay", + "name": "My shairport box" + }, + "matches": [ + "shairport" + ], + "best": "shairport" + }, + { + "why": "nothing matches", + "device": { + "platform": "Google Cast", + "name": "Nest Mini", + "model": "Google Home Mini" + }, + "matches": [], + "best": null + } + ] +} diff --git a/app/src/test/resources/speaker-report-form.yml b/app/src/test/resources/speaker-report-form.yml new file mode 100644 index 00000000..a13a369a --- /dev/null +++ b/app/src/test/resources/speaker-report-form.yml @@ -0,0 +1,62 @@ +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: | + A bot reads this and updates the [list](../blob/main/README.md): if the speaker is already there your + report is counted, if not it is added. **Only the fields below are used; the log is never copied into the list.** + The AriaCast 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 + - No local protocol + - Other + validations: + required: true + - type: dropdown + id: status + attributes: + label: How does it work? + options: + - Supported + - Supported with quirks + - Unsupported + 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. Needed for a speaker that is not plain "Supported" and is not in the list yet. + - type: textarea + id: details + 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 stays in this issue and is not added to the list. + render: text + - type: input + id: version + attributes: + label: AriaCast version diff --git a/app/src/test/resources/speakers.json b/app/src/test/resources/speakers.json new file mode 100644 index 00000000..f2a88e92 --- /dev/null +++ b/app/src/test/resources/speakers.json @@ -0,0 +1,146 @@ +{ + "schema": 2, + "version": 1, + "updated": "2026-11-27", + "speakers": [ + { + "id": "sonos-airplay2", + "speaker": "Sonos (tested on Play:5)", + "protocol": "AirPlay 2", + "status": "supported", + "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", + "locked": true, + "reports": {} + }, + { + "id": "sonos-dlna", + "speaker": "Sonos (tested on Play:5)", + "protocol": "DLNA", + "status": "supported", + "match": { + "platform": "DLNA", + "mentions": [ + "sonos" + ] + }, + "evidence": "[#48](https://github.com/AriaCast/AriaCast-app/issues/48), reporter: DLNA was working", + "locked": true, + "reports": {} + }, + { + "id": "wiim-dlna-restart", + "speaker": "WiiM (tested on Pro Plus)", + "protocol": "DLNA", + "status": "supported", + "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 + }, + "locked": true, + "reports": {} + }, + { + "id": "shairport-airplay1", + "speaker": "shairport-sync", + "protocol": "AirPlay 1", + "status": "supported", + "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", + "locked": true, + "reports": {} + }, + { + "id": "shairport-airplay2-ptp", + "speaker": "shairport-sync", + "protocol": "AirPlay 2", + "status": "quirks", + "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." + }, + "locked": true, + "reports": {} + }, + { + "id": "appletv-airplay-video-pairing", + "speaker": "Apple TV", + "protocol": "AirPlay (video)", + "status": "quirks", + "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", + "locked": true, + "reports": {} + }, + { + "id": "echo-show5-hub-no-airplay", + "speaker": "Amazon Echo Show 5 (1st gen), Echo Hub", + "protocol": "No local protocol", + "status": "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", + "locked": true, + "reports": {} + } + ] +} diff --git a/docs/ROADMAP-2.0.md b/docs/ROADMAP-2.0.md index a2cb9db1..37c43540 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, "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 |