package win.taptap.musicmanager.client import java.io.BufferedInputStream import java.io.File import java.io.FileInputStream import java.io.InputStream import java.net.URI import javax.sound.sampled.AudioFormat import javax.sound.sampled.AudioInputStream import javax.sound.sampled.AudioSystem import javax.sound.sampled.SourceDataLine import kotlin.concurrent.thread import win.taptap.musicmanager.client.api.Song import win.taptap.musicmanager.client.playback.AudioPlayer /** * Desktop playback through the MP3SPI decoder and a PCM line. Pause/resume is a * decoder loop gate, so no audio device is reopened. * * Seeking restarts the decoder at the requested position. Remote streams ask * the server to transcode from that offset (`timeOffset`); local files skip the * decoded PCM frames. Both keep the reported position aligned with the song. * * Java Sound cannot open a line for the compressed MP3 format itself; the * decoded stream has to be converted to PCM_SIGNED first. Opening the encoded * format fails with "No line matching interface SourceDataLine supporting * format MPEG1L3 ...". */ class DesktopAudioPlayer : AudioPlayer { private var input: InputStream? = null private var stream: AudioInputStream? = null private var line: SourceDataLine? = null private var worker: Thread? = null private val lock = Object() private var currentSource: String? = null private var currentSong: Song? = null private var currentLocal = false private var currentArtwork: String? = null @Volatile private var paused = false @Volatile private var stopped = false @Volatile private var finished = false @Volatile private var framesRead = 0L @Volatile private var baseSeconds = 0.0 private var frameSize = 4 private var frameRate = 44_100f private var duration = 0.0 override fun play( source: String, song: Song, local: Boolean, artworkUri: String?, artworkBytes: ByteArray?, ) { currentSource = source currentSong = song currentLocal = local currentArtwork = artworkUri start(source, song, local, startAtSeconds = 0.0) } private fun start(source: String, song: Song, local: Boolean, startAtSeconds: Double) { stop() finished = false paused = false stopped = false framesRead = 0 baseSeconds = startAtSeconds.coerceAtLeast(0.0) duration = song.duration.toDouble() val requestSource = if (!local && startAtSeconds > 0) { withTimeOffset(source, startAtSeconds) } else { source } val raw = if (local) { FileInputStream(File(requestSource)) } else { val connection = URI(requestSource).toURL().openConnection() connection.connectTimeout = 15_000 connection.readTimeout = 30_000 connection.getInputStream() } val buffered = BufferedInputStream(raw, 128 * 1024) input = buffered val encoded = AudioSystem.getAudioInputStream(buffered) val audio = decodeToPcm(encoded) stream = audio frameSize = audio.format.frameSize.takeIf { it > 0 } ?: 4 frameRate = audio.format.frameRate.takeIf { it > 0 } ?: 44_100f // A remote stream already starts at the whole-second offset; local // files and the fractional part are skipped in the decoded PCM. val skipSeconds = if (local) startAtSeconds else startAtSeconds - kotlin.math.floor(startAtSeconds) if (skipSeconds > 0) { skipPcm(audio, skipSeconds) } val info = javax.sound.sampled.DataLine.Info(SourceDataLine::class.java, audio.format) val dataLine = AudioSystem.getLine(info) as SourceDataLine dataLine.open(audio.format) dataLine.start() line = dataLine worker = thread(isDaemon = true, name = "audiomanager-player") { val buffer = ByteArray(16 * 1024) try { while (!stopped) { synchronized(lock) { while (paused && !stopped) lock.wait() } if (stopped) break val read = audio.read(buffer) if (read < 0) { finished = true break } dataLine.write(buffer, 0, read) framesRead += read.toLong() } dataLine.drain() } catch (_: Throwable) { // Stopping closes the stream; that is expected. } finally { runCatching { dataLine.close() } runCatching { audio.close() } runCatching { buffered.close() } } } } private fun skipPcm(audio: AudioInputStream, seconds: Double) { var remaining = (seconds * frameRate * frameSize).toLong().coerceAtLeast(0L) val buffer = ByteArray(16 * 1024) while (remaining > 0 && !stopped) { val skipped = runCatching { audio.skip(remaining) }.getOrDefault(0L) if (skipped > 0) { remaining -= skipped } else { val read = runCatching { audio.read(buffer, 0, minOf(buffer.size.toLong(), remaining).toInt()) }.getOrDefault(-1) if (read <= 0) break remaining -= read } } } override fun pause() { paused = true } override fun resume() { synchronized(lock) { paused = false lock.notifyAll() } } override fun stop() { stopped = true paused = false synchronized(lock) { lock.notifyAll() } runCatching { line?.stop() } runCatching { line?.flush() } worker?.interrupt() runCatching { worker?.join(400) } runCatching { stream?.close() } runCatching { input?.close() } line = null stream = null input = null worker = null } override fun isPlaying(): Boolean = !paused && !finished && worker?.isAlive == true override fun isFinished(): Boolean = finished override fun positionSeconds(): Double { val seconds = baseSeconds + framesRead.toDouble() / frameSize / frameRate return seconds.coerceIn(0.0, duration.takeIf { it > 0 } ?: seconds) } override fun durationSeconds(): Double = duration override val canSeek: Boolean = true override fun seekTo(seconds: Double) { val source = currentSource ?: return val song = currentSong ?: return val wasPaused = paused start(source, song, currentLocal, seconds.coerceAtLeast(0.0)) if (wasPaused) pause() } override fun release() { stop() } /** Adds the server's `timeOffset` parameter, replacing an earlier one. */ private fun withTimeOffset(source: String, seconds: Double): String { val cleaned = source.replace(Regex("[?&]timeOffset=\\d+"), "") val separator = if (cleaned.contains('?')) "&" else "?" return "$cleaned${separator}timeOffset=${seconds.toInt()}" } } /** * MP3SPI hands back a stream whose format is the compressed MPEG one. The audio * device only understands uncompressed PCM, so convert to 16-bit signed PCM at * the source sample rate before opening the line. */ internal fun decodeToPcm(encoded: AudioInputStream): AudioInputStream { val pcm = encoded.format.toPcmFormat() if (encoded.format.encoding == AudioFormat.Encoding.PCM_SIGNED) return encoded return AudioSystem.getAudioInputStream(pcm, encoded) } internal fun AudioFormat.toPcmFormat(): AudioFormat { val rate = sampleRate.takeIf { it > 0 } ?: 44_100f val channelCount = channels.takeIf { it > 0 } ?: 2 return AudioFormat( AudioFormat.Encoding.PCM_SIGNED, rate, 16, channelCount, channelCount * 2, rate, false, ) }