diff --git a/app/src/main/java/dev/daubney/scrobbled/data/recognition/AudioRecordRecorder.kt b/app/src/main/java/dev/daubney/scrobbled/data/recognition/AudioRecordRecorder.kt new file mode 100644 index 0000000..0c9d1ae --- /dev/null +++ b/app/src/main/java/dev/daubney/scrobbled/data/recognition/AudioRecordRecorder.kt @@ -0,0 +1,51 @@ +package dev.daubney.scrobbled.data.recognition + +import android.media.AudioFormat +import android.media.AudioRecord +import android.media.MediaRecorder +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ensureActive +import kotlinx.coroutines.withContext +import java.io.ByteArrayOutputStream +import kotlin.coroutines.coroutineContext + +/** Records from the microphone as 8 kHz mono 16-bit PCM, the format recognition services expect. */ +class AudioRecordRecorder : AudioRecorder { + override suspend fun record(seconds: Int, onProgress: (Float) -> Unit): AudioClip = withContext(Dispatchers.IO) { + val minBuffer = AudioRecord.getMinBufferSize(RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT) + if (minBuffer <= 0) throw ListenException("No microphone available") + val recorder = try { + AudioRecord( + MediaRecorder.AudioSource.MIC, RATE, AudioFormat.CHANNEL_IN_MONO, + AudioFormat.ENCODING_PCM_16BIT, maxOf(minBuffer, RATE * 2), + ) + } catch (e: SecurityException) { + throw ListenException("Microphone permission is needed to listen") + } + if (recorder.state != AudioRecord.STATE_INITIALIZED) { + recorder.release() + throw ListenException("Couldn't open the microphone") + } + val target = RATE * seconds * 2 + val out = ByteArrayOutputStream(target) + val buffer = ByteArray(minBuffer) + try { + recorder.startRecording() + while (out.size() < target) { + coroutineContext.ensureActive() + val n = recorder.read(buffer, 0, buffer.size) + if (n < 0) throw ListenException("Lost the microphone") + out.write(buffer, 0, n) + onProgress((out.size().toFloat() / target).coerceAtMost(1f)) + } + } finally { + runCatching { recorder.stop() } + recorder.release() + } + AudioClip(out.toByteArray(), RATE) + } + + private companion object { + const val RATE = 8000 + } +} diff --git a/app/src/main/java/dev/daubney/scrobbled/data/recognition/FakeRecognizer.kt b/app/src/main/java/dev/daubney/scrobbled/data/recognition/FakeRecognizer.kt new file mode 100644 index 0000000..b45b70c --- /dev/null +++ b/app/src/main/java/dev/daubney/scrobbled/data/recognition/FakeRecognizer.kt @@ -0,0 +1,28 @@ +package dev.daubney.scrobbled.data.recognition + +import dev.daubney.scrobbled.data.search.TrackResult +import kotlinx.coroutines.delay + +/** + * Stand-in for a real recognition service (ACRCloud) until its keys are available. It ignores the + * audio and cycles through a few known songs, reporting "no match" every fourth call so the + * not-found path can be exercised too. + */ +class FakeRecognizer(private val latencyMs: Long = 1_500) : Recognizer { + private var calls = 0 + + override suspend fun recognize(clip: AudioClip): TrackResult? { + delay(latencyMs) + val n = calls++ + if (n % 4 == 3) return null + return songs[n % 4 % songs.size] + } + + private companion object { + val songs = listOf( + TrackResult("", "Radiohead", "Reckoner", "In Rainbows", 290), + TrackResult("", "Boards of Canada", "Roygbiv", "Music Has the Right to Children", 151), + TrackResult("", "Portishead", "Glory Box", "Dummy", 305), + ) + } +} diff --git a/app/src/main/java/dev/daubney/scrobbled/data/recognition/Recognizer.kt b/app/src/main/java/dev/daubney/scrobbled/data/recognition/Recognizer.kt new file mode 100644 index 0000000..1217b29 --- /dev/null +++ b/app/src/main/java/dev/daubney/scrobbled/data/recognition/Recognizer.kt @@ -0,0 +1,24 @@ +package dev.daubney.scrobbled.data.recognition + +import dev.daubney.scrobbled.data.search.TrackResult + +/** Raw microphone audio: 16-bit signed little-endian mono PCM. */ +class AudioClip(val pcm: ByteArray, val sampleRate: Int) { + val seconds get() = pcm.size / 2.0 / sampleRate +} + +/** A failure the user can act on (no microphone, no network, service refused). */ +class ListenException(message: String) : Exception(message) + +interface AudioRecorder { + /** Records [seconds] of audio, reporting progress 0..1. Cancelling the coroutine stops the microphone. */ + suspend fun record(seconds: Int, onProgress: (Float) -> Unit): AudioClip +} + +interface Recognizer { + /** + * Identifies the song in [clip], or returns null when nothing matched. The result's `mbid` is the + * MusicBrainz recording id when the service provides one, otherwise empty. + */ + suspend fun recognize(clip: AudioClip): TrackResult? +} diff --git a/app/src/main/java/dev/daubney/scrobbled/data/scrobble/ScrobbleRepository.kt b/app/src/main/java/dev/daubney/scrobbled/data/scrobble/ScrobbleRepository.kt index 6f5acc0..e7b99a1 100644 --- a/app/src/main/java/dev/daubney/scrobbled/data/scrobble/ScrobbleRepository.kt +++ b/app/src/main/java/dev/daubney/scrobbled/data/scrobble/ScrobbleRepository.kt @@ -18,6 +18,9 @@ enum class SubmitResult { interface ScrobbleRepository { /** Submits one scrobble. Throws if it can't be accepted and isn't worth retrying. */ suspend fun submit(draft: TrackDraft): SubmitResult + + /** Announces what's playing right now. Not queued: it's only meaningful for a few minutes. */ + suspend fun setNowPlaying(draft: TrackDraft) } class DefaultScrobbleRepository( @@ -51,4 +54,16 @@ class DefaultScrobbleRepository( if (queue.count() > 0) scheduler.schedule() return SubmitResult.Sent } + + override suspend fun setNowPlaying(draft: TrackDraft) { + if (draft.artist.isBlank()) throw IllegalArgumentException("Enter an artist") + if (draft.track.isBlank()) throw IllegalArgumentException("Enter a track title") + val creds = auth.current() ?: throw SessionExpiredException() + try { + lastFmFor(creds.serverUrl, creds.apiKey, creds.apiSecret) + .updateNowPlaying(creds.sessionKey, draft.toScrobbleTrack()) + } catch (e: LastFmException) { + throw if (e.isInvalidSession) SessionExpiredException() else e + } + } } diff --git a/app/src/test/java/dev/daubney/scrobbled/data/recognition/FakeRecognizerTest.kt b/app/src/test/java/dev/daubney/scrobbled/data/recognition/FakeRecognizerTest.kt new file mode 100644 index 0000000..45cb60e --- /dev/null +++ b/app/src/test/java/dev/daubney/scrobbled/data/recognition/FakeRecognizerTest.kt @@ -0,0 +1,25 @@ +package dev.daubney.scrobbled.data.recognition + +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class FakeRecognizerTest { + private val clip = AudioClip(ByteArray(16_000), 8000) + + @Test + fun clipReportsItsLength() = assertEquals(1.0, clip.seconds, 0.001) + + @Test + fun cyclesSongsAndMissesEveryFourthCall() = runTest { + val r = FakeRecognizer(latencyMs = 0) + val results = List(8) { r.recognize(clip) } + assertEquals("Reckoner", results[0]?.track) + assertEquals("Roygbiv", results[1]?.track) + assertEquals("Glory Box", results[2]?.track) + assertNull(results[3]) + assertEquals("Reckoner", results[4]?.track) + assertNull(results[7]) + } +} diff --git a/app/src/test/java/dev/daubney/scrobbled/data/scrobble/ScrobbleRepositoryTest.kt b/app/src/test/java/dev/daubney/scrobbled/data/scrobble/ScrobbleRepositoryTest.kt index 06e4dba..63094dc 100644 --- a/app/src/test/java/dev/daubney/scrobbled/data/scrobble/ScrobbleRepositoryTest.kt +++ b/app/src/test/java/dev/daubney/scrobbled/data/scrobble/ScrobbleRepositoryTest.kt @@ -127,4 +127,35 @@ class ScrobbleRepositoryTest { repo.submit(draft) assertEquals(0, scheduler.calls) } + + @Test + fun setNowPlayingSendsUpdateNowPlayingWithoutQueueing() = runTest { + server.enqueue(MockResponse().setBody("""{"nowplaying":{"track":{"#text":"T"}}}""")) + repo.setNowPlaying(TrackDraft(artist = "A", track = "T", album = "Al", durationSeconds = 200)) + val body = URLDecoder.decode(server.takeRequest().body.readUtf8(), "UTF-8") + assertTrue(body.contains("method=track.updateNowPlaying")) + assertTrue(body.contains("artist=A")) + assertTrue(body.contains("duration=200")) + assertTrue(body.contains("sk=sess")) + assertEquals(0, queue.all.size) + } + + @Test + fun setNowPlayingDoesNotQueueOnFailure() = runTest { + server.enqueue(MockResponse().setResponseCode(502).setBody("bad")) + try { repo.setNowPlaying(TrackDraft(artist = "A", track = "T")); fail() } catch (e: LastFmException) { } + assertEquals(0, queue.all.size) + } + + @Test + fun setNowPlayingMapsInvalidSession() = runTest { + server.enqueue(MockResponse().setResponseCode(403).setBody("""{"error":9,"message":"Invalid session key"}""")) + try { repo.setNowPlaying(TrackDraft(artist = "A", track = "T")); fail() } catch (e: SessionExpiredException) { } + } + + @Test + fun setNowPlayingNeedsArtistAndTrack() = runTest { + try { repo.setNowPlaying(TrackDraft(artist = "A", track = " ")); fail() } catch (e: IllegalArgumentException) { } + assertEquals(0, server.requestCount) + } } diff --git a/app/src/test/java/dev/daubney/scrobbled/ui/add/AddViewModelTest.kt b/app/src/test/java/dev/daubney/scrobbled/ui/add/AddViewModelTest.kt index ff40913..797bde8 100644 --- a/app/src/test/java/dev/daubney/scrobbled/ui/add/AddViewModelTest.kt +++ b/app/src/test/java/dev/daubney/scrobbled/ui/add/AddViewModelTest.kt @@ -29,6 +29,7 @@ private class FakeScrobbles : ScrobbleRepository { submitted += draft return result } + override suspend fun setNowPlaying(draft: TrackDraft) {} } private class FakeSearch : TrackSearch {