package eu.friedcutlet.yokan.services.tts import kotlinx.coroutines.delay import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.withContext import java.util.concurrent.TimeUnit actual fun createPlatformTextToSpeechService(): TextToSpeechService = DesktopTextToSpeechService() private class DesktopTextToSpeechService : TextToSpeechService { @Volatile private var currentProcess: Process? = null // Probe once per process instead of forking `which` for every paragraph. private val hasSpdSay by lazy { commandExists("spd-say") } private val hasEspeak by lazy { commandExists("espeak") } override suspend fun voices(language: String?): List = listOf("System default") override suspend fun speak( text: String, request: TextToSpeechRequest, onProgress: (startOffset: Int, endOffset: Int) -> Unit, ) { if (text.isBlank()) return stop() val command = pickCommand(text, request) ?: return val process = runCatching { ProcessBuilder(command).inheritIO().start() }.getOrNull() ?: return currentProcess = process try { val wordsPerMinute = (request.speechRate * 350.0).toInt().coerceIn(80, 500) val wordDelayMillis = (60_000L / wordsPerMinute).coerceAtLeast(40L) Regex("\\S+").findAll(text).forEach { word -> if (!process.isAlive) return@forEach onProgress(word.range.first, word.range.last + 1) delay(wordDelayMillis) } while (process.isAlive) delay(50) } finally { withContext(NonCancellable) { terminate(process) } if (currentProcess === process) currentProcess = null } } override suspend fun stop() { val process = currentProcess ?: return terminate(process) if (currentProcess === process) currentProcess = null } private suspend fun terminate(process: Process) = withContext(Dispatchers.IO) { if (process.isAlive) process.destroy() if (!process.waitFor(2, TimeUnit.SECONDS)) { process.destroyForcibly() process.waitFor() } Unit } private fun pickCommand(text: String, request: TextToSpeechRequest): List? { val os = System.getProperty("os.name").orEmpty().lowercase() val wordsPerMinute = (request.speechRate * 350.0).toInt().coerceIn(80, 500) return when { os.contains("mac") -> buildList { add("say") request.voice?.takeIf { it.isNotBlank() }?.let { add("-v") add(it) } add("-r") add(wordsPerMinute.toString()) add(text) } os.contains("linux") -> when { hasSpdSay -> listOf("spd-say", "-r", ((request.speechRate - 0.5) * 200).toInt().toString(), text) hasEspeak -> listOf( "espeak", "-s", wordsPerMinute.toString(), "-p", (request.pitch * 50.0).toInt().coerceIn(0, 99).toString(), text, ) else -> null } os.contains("win") -> listOf( "powershell", "-Command", "Add-Type -AssemblyName System.Speech;" + "\$s=New-Object System.Speech.Synthesis.SpeechSynthesizer;" + "\$s.Rate=${((request.speechRate - 0.5) * 10).toInt().coerceIn(-10, 10)};" + "\$s.Speak(\"${text.replace("\"", " ")}\")", ) else -> null } } private fun commandExists(name: String): Boolean = runCatching { ProcessBuilder("which", name) .redirectErrorStream(true) .redirectOutput(ProcessBuilder.Redirect.DISCARD) .start() .waitFor() == 0 }.getOrDefault(false) }