Skip to content

Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.

feat(podcast): synthesize_podcast_dialogue, two hosts with silence gaps

Durganshu Mishra704532f550d1
diff --git a/app/src/main/java/com/gotcha/data/SettingsRepository.kt b/app/src/main/java/com/gotcha/data/SettingsRepository.kt
index cb6a8c4..1d41be8 100644
--- a/app/src/main/java/com/gotcha/data/SettingsRepository.kt
+++ b/app/src/main/java/com/gotcha/data/SettingsRepository.kt
@@ -63,6 +63,11 @@ data class Settings(
val ttsApiKey: String = "",
val ttsApiModel: String = "",
val ttsVoice: String = "",
+ // Voices for the two hosts of synthesize_podcast_dialogue. Blank falls back
+ // to [ttsVoice] for host A and to a deterministically different voice from
+ // the model's own list for host B, so the hosts stay distinguishable.
+ val podcastHostAVoice: String = "",
+ val podcastHostBVoice: String = "",
val sttProvider: AudioProvider = AudioProvider.ANDROID,
val sttApiBaseUrl: String = "",
val sttApiKey: String = "",
@@ -382,6 +387,8 @@ class SettingsRepository(context: Context) : SettingsStore {
ttsApiKey = string(KEY_TTS_API_KEY),
ttsApiModel = string(KEY_TTS_API_MODEL),
ttsVoice = string(KEY_TTS_VOICE),
+ podcastHostAVoice = string(KEY_PODCAST_HOST_A_VOICE),
+ podcastHostBVoice = string(KEY_PODCAST_HOST_B_VOICE),
sttProvider = runCatching {
AudioProvider.valueOf(string(KEY_STT_PROVIDER, "ANDROID"))
}.getOrDefault(AudioProvider.ANDROID),
@@ -448,6 +455,8 @@ class SettingsRepository(context: Context) : SettingsStore {
.putString(KEY_TTS_API_KEY, settings.ttsApiKey)
.putString(KEY_TTS_API_MODEL, settings.ttsApiModel)
.putString(KEY_TTS_VOICE, settings.ttsVoice)
+ .putString(KEY_PODCAST_HOST_A_VOICE, settings.podcastHostAVoice)
+ .putString(KEY_PODCAST_HOST_B_VOICE, settings.podcastHostBVoice)
.putString(KEY_STT_PROVIDER, settings.sttProvider.name)
.putString(KEY_STT_API_URL, settings.sttApiBaseUrl)
.putString(KEY_STT_API_KEY, settings.sttApiKey)
@@ -555,6 +564,8 @@ class SettingsRepository(context: Context) : SettingsStore {
const val KEY_TTS_API_KEY = "tts_api_key"
const val KEY_TTS_API_MODEL = "tts_api_model"
const val KEY_TTS_VOICE = "tts_voice"
+ const val KEY_PODCAST_HOST_A_VOICE = "podcast_host_a_voice"
+ const val KEY_PODCAST_HOST_B_VOICE = "podcast_host_b_voice"
const val KEY_STT_PROVIDER = "stt_provider"
const val KEY_STT_API_URL = "stt_api_url"
const val KEY_STT_API_KEY = "stt_api_key"
diff --git a/app/src/main/java/com/gotcha/tools/PodcastAudio.kt b/app/src/main/java/com/gotcha/tools/PodcastAudio.kt
index dba4d99..c7c6197 100644
--- a/app/src/main/java/com/gotcha/tools/PodcastAudio.kt
+++ b/app/src/main/java/com/gotcha/tools/PodcastAudio.kt
@@ -127,6 +127,44 @@ object PodcastAudio {
/** [wavInfo] for a file already on disk. */
fun wavInfo(file: File): WavInfo? = runCatching { wavInfo(file.readBytes()) }.getOrNull()
+ private const val PCM_FORMAT_CODE = 1
+ private const val PCM16_BYTES_PER_SAMPLE = 2
+ private const val FMT_CHUNK_BYTES = 16
+ private const val BITS_PER_BYTE = 8
+
+ /**
+ * A canonical PCM16 WAV of digital silence, used as the breathing gap
+ * between dialogue turns. Generated at the [sampleRate]/[channels] of the
+ * speech it sits between rather than at some fixed rate, so the joiner
+ * sees a homogeneous sequence instead of resampling a mismatched clip at
+ * every turn boundary.
+ */
+ fun silenceWav(durationMs: Long, sampleRate: Int, channels: Int): ByteArray {
+ require(durationMs >= 0 && sampleRate > 0 && channels > 0) { "invalid silence parameters" }
+ val frameBytes = channels * PCM16_BYTES_PER_SAMPLE
+ val dataBytes = (durationMs * sampleRate / MILLIS_PER_SECOND).toInt() * frameBytes
+ val out = java.io.ByteArrayOutputStream(MIN_WAV_BYTES + dataBytes)
+ fun ascii(s: String) = s.forEach { out.write(it.code) }
+ fun le32(v: Int) = repeat(4) { out.write((v shr (BITS_PER_BYTE * it)) and 0xFF) }
+ fun le16(v: Int) = repeat(2) { out.write((v shr (BITS_PER_BYTE * it)) and 0xFF) }
+
+ ascii("RIFF")
+ le32(MIN_WAV_BYTES - CHUNK_HEADER_BYTES + dataBytes)
+ ascii("WAVE")
+ ascii("fmt ")
+ le32(FMT_CHUNK_BYTES)
+ le16(PCM_FORMAT_CODE)
+ le16(channels)
+ le32(sampleRate)
+ le32(sampleRate * frameBytes)
+ le16(frameBytes)
+ le16(PCM16_BYTES_PER_SAMPLE * BITS_PER_BYTE)
+ ascii("data")
+ le32(dataBytes)
+ out.write(ByteArray(dataBytes))
+ return out.toByteArray()
+ }
+
private fun ByteArray.ascii(offset: Int, expected: String): Boolean {
if (offset + expected.length > size) return false
return expected.withIndex().all { (i, c) -> this[offset + i] == c.code.toByte() }
diff --git a/app/src/main/java/com/gotcha/tools/PodcastTool.kt b/app/src/main/java/com/gotcha/tools/PodcastTool.kt
index 22d0e03..6a68bc1 100644
--- a/app/src/main/java/com/gotcha/tools/PodcastTool.kt
+++ b/app/src/main/java/com/gotcha/tools/PodcastTool.kt
@@ -14,16 +14,18 @@ import java.io.File
import kotlin.coroutines.coroutineContext
/**
- * Turns a written script into a spoken audio file — a single-voice podcast.
+ * Turns written text into spoken audio files — podcasts.
*
- * The synthesis reuses the same OpenAI-compatible `/audio/speech` endpoint the
- * voice features already talk through, but deliberately not via
+ * Two entry points share one pipeline: [synthesize] narrates a script in a
+ * single voice, [synthesizeDialogue] alternates two host voices with a short
+ * silence between turns. Both reuse the OpenAI-compatible `/audio/speech`
+ * endpoint the voice features already talk through, but deliberately not via
* [com.gotcha.audio.TtsEngine]: that class is hardwired to play what it
- * fetches, while this one needs the raw WAV bytes on disk. The script is
- * sanitized exactly as spoken replies are, split at sentence boundaries (the
- * endpoint has input-length limits a whole script would blow through),
- * synthesized segment by segment into the cache dir, and joined on-device by
- * [MediaExport] into an `.m4a` under `Gotcha/Podcasts`.
+ * fetches, while this one needs the raw WAV bytes on disk. Text is sanitized
+ * exactly as spoken replies are, split at sentence boundaries (the endpoint
+ * has input-length limits a whole script would blow through), synthesized
+ * segment by segment into the cache dir, and joined on-device by [MediaExport]
+ * into an `.m4a` under `Gotcha/Podcasts`.
*
* `.m4a` is the canonical output because it needs nothing beyond what ships in
* the app. MP3 exists only through Termux's ffmpeg ([MediaConvertTool]), so a
@@ -56,6 +58,9 @@ class PodcastTool(
api.synthesize(text, model, voice)
}
+ /** One turn of a dialogue script, as the model writes it. */
+ data class DialogueLine(val speaker: String, val text: String)
+
private val resolver = FileResolver(context)
companion object {
@@ -77,9 +82,17 @@ class PodcastTool(
/** Same ceiling as media_edit's re-encode guard — assembly re-encodes everything. */
const val MAX_TOTAL_DURATION_MS = MediaEditTool.MAX_REENCODE_DURATION_MS
+ /**
+ * Breathing room between dialogue turns. Long enough to read as a
+ * speaker change, short enough not to read as dead air.
+ */
+ const val DIALOGUE_GAP_MS = 300L
+
private const val TTS_TIMEOUT_SECONDS = 120L
private const val FORMAT_M4A = "m4a"
private const val FORMAT_MP3 = "mp3"
+ private const val SPEAKER_A = "A"
+ private const val SPEAKER_B = "B"
/** Intermediate for the MP3 detour. Ends in `.m4a` so ffmpeg and the salvage rename both see AAC. */
private const val TMP_SUFFIX = ".podcast-tmp.m4a"
@@ -92,20 +105,29 @@ class PodcastTool(
data class Failed(val result: ToolResult) : Resolved
}
- /** Everything one synthesis run carries between its stages. */
- private data class Job(
+ /** A single TTS request: what to say, and with which model and voice. */
+ private data class SpeechSegment(val text: String, val model: String, val voice: String)
+
+ /**
+ * Everything one synthesis run carries between its stages. [groups] are
+ * lists of segments; the silence gap is inserted *between groups*, never
+ * between the chunks of one over-long piece of text.
+ */
+ private data class SynthesisJob(
val backend: TtsBackend,
- val text: String,
- val model: String,
- val voice: String,
+ val groups: List<List<SpeechSegment>>,
+ val gapMs: Long,
val tempDir: File,
val destination: File,
val wantMp3: Boolean,
val baseName: String,
val overwrite: Boolean,
- val degradeNote: String
+ val notes: String,
+ val voiceLabel: String
)
+ // ---- entry points ----
+
@Suppress("ReturnCount", "LongParameterList")
suspend fun synthesize(
script: String,
@@ -117,25 +139,100 @@ class PodcastTool(
): ToolResult {
val settings = loadSettings()
credentialError(settings)?.let { return it }
-
val requestedFormat = normaliseFormat(format, outputName) ?: return unsupportedFormat(format, outputName)
val resolvedModel = (model ?: settings.ttsApiModel).trim()
if (resolvedModel.isBlank()) return noModelConfigured()
val text = SpeechTextSanitizer.sanitize(script)
- if (text.isBlank()) {
+ scriptError(text.length, emptyText = text.isBlank())?.let { return it }
+
+ val backend = ttsBackendFactory(settings.effectiveTtsBaseUrl, settings.effectiveTtsApiKey)
+ val resolvedVoice = resolveVoice(voice, settings.ttsVoice, backend, resolvedModel)
+ ?: return noVoiceResolvable(resolvedModel)
+
+ val segments = PodcastAudio.chunk(text, MAX_CHUNK_CHARS)
+ .map { SpeechSegment(it, resolvedModel, resolvedVoice) }
+ return runJob(
+ backend = backend,
+ groups = listOf(segments),
+ gapMs = 0L,
+ outputName = outputName,
+ requestedFormat = requestedFormat,
+ overwrite = overwrite,
+ notes = "",
+ voiceLabel = "voice '$resolvedVoice'"
+ )
+ }
+
+ @Suppress("ReturnCount", "LongParameterList")
+ suspend fun synthesizeDialogue(
+ lines: List<DialogueLine>,
+ outputName: String,
+ hostAVoice: String? = null,
+ hostBVoice: String? = null,
+ hostAModel: String? = null,
+ hostBModel: String? = null,
+ format: String? = null,
+ overwrite: Boolean = false
+ ): ToolResult {
+ val settings = loadSettings()
+ credentialError(settings)?.let { return it }
+ val requestedFormat = normaliseFormat(format, outputName) ?: return unsupportedFormat(format, outputName)
+ val modelA = (hostAModel ?: settings.ttsApiModel).trim()
+ val modelB = (hostBModel ?: modelA).trim()
+ if (modelA.isBlank()) return noModelConfigured()
+
+ val turns = lines.map { it.copy(text = SpeechTextSanitizer.sanitize(it.text)) }
+ .filter { it.text.isNotBlank() }
+ val badSpeaker = turns.firstOrNull { it.speaker != SPEAKER_A && it.speaker != SPEAKER_B }
+ if (badSpeaker != null) {
return ToolResult.error(
- "The script is empty once markdown, code and emoji are stripped for speech. " +
- "Write the narration as plain prose and try again."
+ "speaker '${badSpeaker.speaker}' is not a host — every line's speaker must be exactly " +
+ "'$SPEAKER_A' or '$SPEAKER_B'."
)
}
- if (text.length > MAX_SCRIPT_CHARS) {
- return ToolResult.error(
- "The script is ${text.length} characters; the limit is $MAX_SCRIPT_CHARS (~25 minutes of " +
- "speech). Split it into parts and synthesize each as its own file."
- )
+ scriptError(turns.sumOf { it.text.length }, emptyText = turns.isEmpty())?.let { return it }
+
+ val backend = ttsBackendFactory(settings.effectiveTtsBaseUrl, settings.effectiveTtsApiKey)
+ val voiceA = resolveVoice(hostAVoice, settings.podcastHostAVoice.ifBlank { settings.ttsVoice }, backend, modelA)
+ ?: return noVoiceResolvable(modelA)
+ val voiceB = resolveHostBVoice(hostBVoice, settings, backend, modelB, voiceA)
+ val sameVoiceNote = if (voiceA == voiceB) {
+ " Both hosts ended up with voice '$voiceA' — no second voice could be found automatically; pass " +
+ "host_b_voice or set one in Settings → Speech to make them distinguishable."
+ } else {
+ ""
+ }
+
+ val groups = turns.map { turn ->
+ val (model, voice) = if (turn.speaker == SPEAKER_A) modelA to voiceA else modelB to voiceB
+ PodcastAudio.chunk(turn.text, MAX_CHUNK_CHARS).map { SpeechSegment(it, model, voice) }
}
+ return runJob(
+ backend = backend,
+ groups = groups,
+ gapMs = DIALOGUE_GAP_MS,
+ outputName = outputName,
+ requestedFormat = requestedFormat,
+ overwrite = overwrite,
+ notes = sameVoiceNote,
+ voiceLabel = "voices '$voiceA' (host A) and '$voiceB' (host B)"
+ )
+ }
+ // ---- the shared pipeline ----
+
+ @Suppress("ReturnCount", "LongParameterList")
+ private suspend fun runJob(
+ backend: TtsBackend,
+ groups: List<List<SpeechSegment>>,
+ gapMs: Long,
+ outputName: String,
+ requestedFormat: String,
+ overwrite: Boolean,
+ notes: String,
+ voiceLabel: String
+ ): ToolResult {
val wantMp3 = requestedFormat == FORMAT_MP3 && termuxUsable()
val degradeNote = if (requestedFormat == FORMAT_MP3 && !wantMp3) {
" MP3 was requested, but that conversion runs through Termux's ffmpeg, which is not available on " +
@@ -149,21 +246,13 @@ class PodcastTool(
is Resolved.Failed -> return r.result
is Resolved.Ok -> r.file
}
-
- val backend = ttsBackendFactory(settings.effectiveTtsBaseUrl, settings.effectiveTtsApiKey)
- val resolvedVoice = resolveVoice(voice, settings, backend, resolvedModel)
- ?: return ToolResult.error(
- "No TTS voice is set and the API's voice list for '$resolvedModel' could not be fetched. " +
- "Pass voice explicitly, or ask the user to pick one in Settings → Speech."
- )
-
val tempDir = File(context.cacheDir, "podcast_${System.currentTimeMillis()}")
return try {
produce(
- Job(
- backend = backend, text = text, model = resolvedModel, voice = resolvedVoice,
- tempDir = tempDir, destination = destination, wantMp3 = wantMp3,
- baseName = baseName, overwrite = overwrite, degradeNote = degradeNote
+ SynthesisJob(
+ backend = backend, groups = groups, gapMs = gapMs, tempDir = tempDir,
+ destination = destination, wantMp3 = wantMp3, baseName = baseName,
+ overwrite = overwrite, notes = notes + degradeNote, voiceLabel = voiceLabel
)
)
} finally {
@@ -171,35 +260,44 @@ class PodcastTool(
}
}
- // ---- the pipeline ----
-
@Suppress("ReturnCount")
- private suspend fun produce(job: Job): ToolResult {
+ private suspend fun produce(job: SynthesisJob): ToolResult {
job.tempDir.mkdirs()
- val chunks = PodcastAudio.chunk(job.text, MAX_CHUNK_CHARS)
- val wavs = mutableListOf<File>()
+ val totalSegments = job.groups.sumOf { it.size }
+ val files = mutableListOf<File>()
+ val silenceByFormat = mutableMapOf<Pair<Int, Int>, File>()
var totalMs = 0L
- for ((index, chunk) in chunks.withIndex()) {
- coroutineContext.ensureActive()
- val bytes = job.backend.synthesize(chunk, job.model, job.voice).getOrElse { e ->
- return ToolResult.error(
- "The TTS request failed on segment ${index + 1} of ${chunks.size}: " +
- "${e.message?.take(ERROR_DETAIL_CHARS) ?: "no detail"}. Nothing was written."
+ var index = 0
+ var lastWav: PodcastAudio.WavInfo? = null
+ for ((groupIndex, group) in job.groups.withIndex()) {
+ for (segment in group) {
+ coroutineContext.ensureActive()
+ index++
+ val bytes = job.backend.synthesize(segment.text, segment.model, segment.voice).getOrElse { e ->
+ return ToolResult.error(
+ "The TTS request failed on segment $index of $totalSegments: " +
+ "${e.message?.take(ERROR_DETAIL_CHARS) ?: "no detail"}. Nothing was written."
+ )
+ }
+ val info = PodcastAudio.wavInfo(bytes) ?: return ToolResult.error(
+ "The TTS endpoint returned something that is not WAV audio for segment $index. " +
+ "The model name or voice may be wrong for this provider — check them against the " +
+ "provider's model list."
)
+ totalMs += info.durationMs
+ if (totalMs > MAX_TOTAL_DURATION_MS) return audioTooLong()
+ files += File(job.tempDir, "segment_%03d.wav".format(index)).apply { writeBytes(bytes) }
+ lastWav = info
}
- val info = PodcastAudio.wavInfo(bytes) ?: return ToolResult.error(
- "The TTS endpoint returned something that is not WAV audio for segment ${index + 1}. " +
- "The model name or voice may be wrong for this provider — check them against the " +
- "provider's model list."
- )
- totalMs += info.durationMs
- if (totalMs > MAX_TOTAL_DURATION_MS) {
- return ToolResult.error(
- "The synthesized audio passed ${MediaTimeSpec.format(MAX_TOTAL_DURATION_MS)} before the " +
- "script was finished. Shorten the script or split it into parts."
- )
+ val wav = lastWav
+ if (job.gapMs > 0 && groupIndex < job.groups.lastIndex && wav != null) {
+ files += silenceByFormat.getOrPut(wav.sampleRate to wav.channels) {
+ File(job.tempDir, "gap_${wav.sampleRate}_${wav.channels}.wav").apply {
+ writeBytes(PodcastAudio.silenceWav(job.gapMs, wav.sampleRate, wav.channels))
+ }
+ }
+ totalMs += job.gapMs
}
- wavs += File(job.tempDir, "segment_%03d.wav".format(index)).apply { writeBytes(bytes) }
}
val m4aOut = if (job.wantMp3) {
@@ -207,15 +305,15 @@ class PodcastTool(
} else {
job.destination
}
- assemble(wavs, job.tempDir, m4aOut)?.let { return it }
+ assemble(files, job.tempDir, m4aOut)?.let { return it }
val (finalFile, conversionNote) = if (job.wantMp3) convertToMp3(m4aOut, job) else job.destination to ""
GotchaStorage.publishToGallery(context, finalFile)
return ToolResult.ok(
"Created the podcast at '${finalFile.canonicalPath}' — ${MediaTimeSpec.format(totalMs)} of audio, " +
- "${resolver.formatSize(finalFile.length())}, synthesized as ${chunks.size} segment(s) with " +
- "voice '${job.voice}' and assembled on-device. It is visible in the phone's Files app under " +
- "Gotcha/Podcasts." + job.degradeNote + conversionNote
+ "${resolver.formatSize(finalFile.length())}, synthesized as $totalSegments segment(s) with " +
+ "${job.voiceLabel} and assembled on-device. It is visible in the phone's Files app under " +
+ "Gotcha/Podcasts." + job.notes + conversionNote
)
}
@@ -223,7 +321,8 @@ class PodcastTool(
* Joins the segment WAVs into [output] as AAC. Temp files skip
* [FileResolver] on purpose: they live in the app's own cache, where a
* permission check has nothing to say — the shared-storage checks already
- * ran on the final destination.
+ * ran on the final destination. Batching counts every file, silence gaps
+ * included — a 10-line dialogue is already 19 concat inputs.
*/
private suspend fun assemble(wavs: List<File>, tempDir: File, output: File): ToolResult? {
output.parentFile?.mkdirs()
@@ -251,7 +350,7 @@ class PodcastTool(
* money is already spent and the audio is already good, so it is salvaged
* as `.m4a` with a note saying what happened and how to finish the job.
*/
- private suspend fun convertToMp3(m4a: File, job: Job): Pair<File, String> {
+ private suspend fun convertToMp3(m4a: File, job: SynthesisJob): Pair<File, String> {
val result = mediaConvert.convert(m4a.absolutePath, job.destination.absolutePath, overwrite = job.overwrite)
if (result.success) {
m4a.delete()
@@ -288,6 +387,23 @@ class PodcastTool(
return null
}
+ private fun scriptError(sanitizedLength: Int, emptyText: Boolean): ToolResult? = when {
+ emptyText -> ToolResult.error(
+ "The script is empty once markdown, code and emoji are stripped for speech. " +
+ "Write the narration as plain prose and try again."
+ )
+ sanitizedLength > MAX_SCRIPT_CHARS -> ToolResult.error(
+ "The script is $sanitizedLength characters; the limit is $MAX_SCRIPT_CHARS (~25 minutes of " +
+ "speech). Split it into parts and synthesize each as its own file."
+ )
+ else -> null
+ }
+
+ private fun audioTooLong(): ToolResult = ToolResult.error(
+ "The synthesized audio passed ${MediaTimeSpec.format(MAX_TOTAL_DURATION_MS)} before the " +
+ "script was finished. Shorten the script or split it into parts."
+ )
+
/** The format arg wins; a recognisable extension on output_name is honoured when the arg is absent. */
private fun normaliseFormat(format: String?, outputName: String): String? {
val requested = format?.trim()?.lowercase().takeUnless { it.isNullOrBlank() }
@@ -306,19 +422,48 @@ class PodcastTool(
"Settings → Speech → Text-to-Speech."
)
+ private fun noVoiceResolvable(model: String): ToolResult = ToolResult.error(
+ "No TTS voice is set and the API's voice list for '$model' could not be fetched. " +
+ "Pass voice explicitly, or ask the user to pick one in Settings → Speech."
+ )
+
private fun resolveVoice(
voiceArg: String?,
- settings: Settings,
+ configuredVoice: String,
backend: TtsBackend,
model: String
): String? {
- val explicit = (voiceArg ?: settings.ttsVoice).trim()
+ val explicit = (voiceArg ?: configuredVoice).trim()
if (explicit.isNotBlank()) return explicit
- val ttsModels = runCatching { backend.listModels() }.getOrDefault(emptyList())
- .filter { it.category == ModelCategory.TTS }
- return (ttsModels.firstOrNull { it.id == model } ?: ttsModels.firstOrNull())?.defaultVoice
+ return ttsModels(backend).let { models ->
+ (models.firstOrNull { it.id == model } ?: models.firstOrNull())?.defaultVoice
+ }
+ }
+
+ /**
+ * Host B must differ from host A to be worth having. With nothing
+ * configured, the first voice in the model's list that is not A's is
+ * chosen — deterministic for a given provider, unlike "the second voice",
+ * which silently collides when A already *is* the second voice.
+ */
+ private fun resolveHostBVoice(
+ voiceArg: String?,
+ settings: Settings,
+ backend: TtsBackend,
+ model: String,
+ voiceA: String
+ ): String {
+ val explicit = (voiceArg ?: settings.podcastHostBVoice).trim()
+ if (explicit.isNotBlank()) return explicit
+ val models = ttsModels(backend)
+ val voices = (models.firstOrNull { it.id == model } ?: models.firstOrNull())?.voices.orEmpty()
+ return voices.firstOrNull { it.id != voiceA }?.id ?: voiceA
}
+ private fun ttsModels(backend: TtsBackend): List<AudioModel> =
+ runCatching { backend.listModels() }.getOrDefault(emptyList())
+ .filter { it.category == ModelCategory.TTS }
+
@Suppress("ReturnCount")
private fun resolveDestination(baseName: String, extension: String, overwrite: Boolean): Resolved {
val target = File(GotchaStorage.podcastsRoot(), "$baseName.$extension")
diff --git a/app/src/main/java/com/gotcha/tools/ToolCategories.kt b/app/src/main/java/com/gotcha/tools/ToolCategories.kt
index 43e7e11..4274b4e 100644
--- a/app/src/main/java/com/gotcha/tools/ToolCategories.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolCategories.kt
@@ -19,7 +19,7 @@ object ToolCategories {
private val backgroundTools = setOf(
"edit", "write_file", "make_directory", "delete_file", "pdf_edit", "media_edit", "media_convert",
- "synthesize_podcast",
+ "synthesize_podcast", "synthesize_podcast_dialogue",
"uninstall_app", "delete_calendar_event", "delete_alarm",
"delete_timer", "edit_alarm",
"toggle_wifi", "toggle_torch",
diff --git a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
index e73c3d7..d7bc656 100644
--- a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
@@ -1509,6 +1509,95 @@ object ToolDefinitions {
}
)
+ val synthesizePodcastDialogue = tool(
+ "synthesize_podcast_dialogue",
+ "Turn a two-host dialogue script into a spoken audio file — a conversational podcast in the " +
+ "NotebookLM style — saved under Gotcha/Podcasts on shared storage. Write the dialogue yourself " +
+ "first: an array of turns, each with speaker 'A' or 'B' and the exact words to speak, as plain " +
+ "prose. The hosts get distinct voices (configured in Settings → Speech, overridable per call, " +
+ "and defaulting to two different voices from the model's own list), with a short natural pause " +
+ "between turns. Length ceiling, output formats and the TTS provider requirement are the same as " +
+ "synthesize_podcast: ~25 minutes, .m4a by default or format='mp3' via Termux's ffmpeg, and an " +
+ "API-based TTS provider — Android's built-in TTS cannot write files.",
+ schema {
+ putJsonObject("properties") {
+ putJsonObject("lines") {
+ put("type", "array")
+ put(
+ "description",
+ "The dialogue in order. Each item is one turn: " +
+ "{\"speaker\": \"A\" or \"B\", \"text\": \"the words to speak\"}."
+ )
+ putJsonObject("items") {
+ put("type", "object")
+ putJsonObject("properties") {
+ putJsonObject("speaker") {
+ put("type", "string")
+ put("description", "'A' or 'B' — which host speaks this turn.")
+ }
+ putJsonObject("text") {
+ put("type", "string")
+ put("description", "What this host says, spoken verbatim. Plain prose only.")
+ }
+ }
+ putJsonArray("required") {
+ add("speaker")
+ add("text")
+ }
+ }
+ }
+ putJsonObject("output_name") {
+ put("type", "string")
+ put(
+ "description",
+ "Base name for the file, e.g. 'ai-news-roundtable'. Slugified and written under " +
+ "Gotcha/Podcasts; a '.mp3' extension selects the mp3 format."
+ )
+ }
+ putJsonObject("host_a_voice") {
+ put("type", "string")
+ put("description", "Voice id for host A. Defaults to the configured podcast host A voice.")
+ }
+ putJsonObject("host_b_voice") {
+ put("type", "string")
+ put(
+ "description",
+ "Voice id for host B. Defaults to the configured podcast host B voice, then to the " +
+ "first voice in the model's list that differs from host A."
+ )
+ }
+ putJsonObject("host_a_model") {
+ put("type", "string")
+ put("description", "TTS model id for host A. Defaults to the configured TTS model.")
+ }
+ putJsonObject("host_b_model") {
+ put("type", "string")
+ put("description", "TTS model id for host B. Defaults to host A's model.")
+ }
+ putJsonObject("format") {
+ put("type", "string")
+ put(
+ "description",
+ "'m4a' (default, works with no setup) or 'mp3' (needs Termux's ffmpeg; degrades to " +
+ ".m4a with a note when unavailable)."
+ )
+ }
+ putJsonObject("overwrite") {
+ put("type", "boolean")
+ put(
+ "description",
+ "Allow replacing an existing output file. Default false, which fails instead of " +
+ "destroying a file the user may still need."
+ )
+ }
+ }
+ putJsonArray("required") {
+ add("lines")
+ add("output_name")
+ }
+ }
+ )
+
val edit = tool(
"edit",
"Replace exact text in a file, for surgical edits without rewriting it. oldString " +
@@ -2743,7 +2832,7 @@ object ToolDefinitions {
// Audio format conversion via Termux ffmpeg (Operator only)
mediaConvert,
// Script-to-speech podcast synthesis (Operator only)
- synthesizePodcast,
+ synthesizePodcast, synthesizePodcastDialogue,
// Content search and file discovery
glob, grep,
// Web search + fetch
diff --git a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
index bb15df1..8443828 100644
--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
@@ -253,6 +253,19 @@ class ToolExecutor(
bitrate = args.requireString("bitrate"),
overwrite = args.requireBoolean("overwrite") ?: false
)
+ "synthesize_podcast_dialogue" -> podcastTool.synthesizeDialogue(
+ lines = parseDialogueLines(args["lines"]) ?: return ToolResult.error(
+ "Missing or invalid required parameter 'lines' — it must be a non-empty array of " +
+ "{\"speaker\": \"A\" or \"B\", \"text\": \"...\"} objects."
+ ),
+ outputName = args.requireString("output_name") ?: return missing("output_name"),
+ hostAVoice = args.requireString("host_a_voice"),
+ hostBVoice = args.requireString("host_b_voice"),
+ hostAModel = args.requireString("host_a_model"),
+ hostBModel = args.requireString("host_b_model"),
+ format = args.requireString("format"),
+ overwrite = args.requireBoolean("overwrite") ?: false
+ )
"synthesize_podcast" -> podcastTool.synthesize(
script = args.requireString("script") ?: return missing("script"),
outputName = args.requireString("output_name") ?: return missing("output_name"),
@@ -650,6 +663,18 @@ class ToolExecutor(
private fun missing(param: String) =
ToolResult.error("Missing or invalid required parameter '$param'.")
+ /** Null on any malformed entry rather than dropping it — a silently skipped turn is a mangled episode. */
+ private fun parseDialogueLines(element: JsonElement?): List<PodcastTool.DialogueLine>? {
+ val array = element as? JsonArray ?: return null
+ if (array.isEmpty()) return null
+ return array.map { item ->
+ val obj = item as? JsonObject ?: return null
+ val speaker = (obj["speaker"] as? JsonPrimitive)?.content?.trim() ?: return null
+ val text = (obj["text"] as? JsonPrimitive)?.content ?: return null
+ PodcastTool.DialogueLine(speaker, text)
+ }
+ }
+
private fun parseTodoItems(element: JsonElement?): List<TodoItem>? {
val array = element as? JsonArray ?: return null
return array.mapNotNull { item ->
diff --git a/app/src/main/java/com/gotcha/ui/SpeechScreen.kt b/app/src/main/java/com/gotcha/ui/SpeechScreen.kt
index 78bac1a..e8b44d4 100644
--- a/app/src/main/java/com/gotcha/ui/SpeechScreen.kt
+++ b/app/src/main/java/com/gotcha/ui/SpeechScreen.kt
@@ -62,6 +62,8 @@ fun SpeechScreen(
var ttsApiKey by remember { mutableStateOf(initial.ttsApiKey) }
var ttsApiModel by remember { mutableStateOf(initial.ttsApiModel) }
var ttsVoice by remember { mutableStateOf(initial.ttsVoice) }
+ var podcastHostAVoice by remember { mutableStateOf(initial.podcastHostAVoice) }
+ var podcastHostBVoice by remember { mutableStateOf(initial.podcastHostBVoice) }
var sttProvider by remember { mutableStateOf(initial.sttProvider) }
var sttApiBaseUrl by remember { mutableStateOf(initial.sttApiBaseUrl) }
var sttApiKey by remember { mutableStateOf(initial.sttApiKey) }
@@ -88,6 +90,8 @@ fun SpeechScreen(
var sttProviderExpanded by remember { mutableStateOf(false) }
var ttsModelExpanded by remember { mutableStateOf(false) }
var ttsVoiceExpanded by remember { mutableStateOf(false) }
+ var hostAVoiceExpanded by remember { mutableStateOf(false) }
+ var hostBVoiceExpanded by remember { mutableStateOf(false) }
var sttModelExpanded by remember { mutableStateOf(false) }
var sttLanguageExpanded by remember { mutableStateOf(false) }
@@ -114,6 +118,8 @@ fun SpeechScreen(
ttsApiKey = ttsApiKey.trim(),
ttsApiModel = ttsApiModel.trim(),
ttsVoice = ttsVoice.trim(),
+ podcastHostAVoice = podcastHostAVoice.trim(),
+ podcastHostBVoice = podcastHostBVoice.trim(),
sttProvider = sttProvider,
sttApiBaseUrl = sttApiBaseUrl.trim(),
sttApiKey = sttApiKey.trim(),
@@ -352,6 +358,42 @@ fun SpeechScreen(
}
AudioProvider.ANDROID, AudioProvider.NONE -> Unit
}
+ // ---- Podcast hosts (synthesize_podcast_dialogue) ----
+ if (ttsProvider.isApiBased()) {
+ Text(
+ "Podcast hosts — the two voices used when the assistant generates a two-host " +
+ "podcast dialogue. Leave blank to use the TTS voice for host A and an " +
+ "automatically chosen different voice for host B.",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ TtsVoicePicker(
+ selectedModel = ttsApiModel,
+ selectedVoice = podcastHostAVoice,
+ availableModels = availableTtsModels,
+ expanded = hostAVoiceExpanded,
+ onExpandedChange = { hostAVoiceExpanded = it },
+ onSelect = {
+ podcastHostAVoice = it
+ hostAVoiceExpanded = false
+ },
+ onClearVoice = { podcastHostAVoice = "" },
+ label = "Podcast Host A Voice (optional)"
+ )
+ TtsVoicePicker(
+ selectedModel = ttsApiModel,
+ selectedVoice = podcastHostBVoice,
+ availableModels = availableTtsModels,
+ expanded = hostBVoiceExpanded,
+ onExpandedChange = { hostBVoiceExpanded = it },
+ onSelect = {
+ podcastHostBVoice = it
+ hostBVoiceExpanded = false
+ },
+ onClearVoice = { podcastHostBVoice = "" },
+ label = "Podcast Host B Voice (optional)"
+ )
+ }
ExposedDropdownMenuBox(
expanded = sttProviderExpanded,
onExpandedChange = { sttProviderExpanded = it }
@@ -564,7 +606,8 @@ private fun TtsVoicePicker(
expanded: Boolean,
onExpandedChange: (Boolean) -> Unit,
onSelect: (String) -> Unit,
- onClearVoice: () -> Unit
+ onClearVoice: () -> Unit,
+ label: String = "TTS Voice (optional)"
) {
val selectedModelObj = availableModels.firstOrNull { it.id == selectedModel }
val voicesList: List<VoiceInfo> = run {
@@ -586,7 +629,7 @@ private fun TtsVoicePicker(
OutlinedTextField(
value = selectedVoice,
onValueChange = onSelect,
- label = { Text("TTS Voice (optional)") },
+ label = { Text(label) },
placeholder = {
if (hasAnyVoices) {
Text("Default ($defaultVoiceLabel) or pick below")
diff --git a/app/src/test/java/com/gotcha/tools/PodcastAudioTest.kt b/app/src/test/java/com/gotcha/tools/PodcastAudioTest.kt
index 9fdcd4b..c2874d4 100644
--- a/app/src/test/java/com/gotcha/tools/PodcastAudioTest.kt
+++ b/app/src/test/java/com/gotcha/tools/PodcastAudioTest.kt
@@ -119,6 +119,25 @@ class PodcastAudioTest {
assertNull(PodcastAudio.wavInfo(byteArrayOf(0xFF.toByte(), 0xFB.toByte()) + ByteArray(100)))
}
+ // ---- silence generation ----
+
+ @Test
+ fun `generated silence is a valid WAV of the requested format and length`() {
+ val info = PodcastAudio.wavInfo(PodcastAudio.silenceWav(1000, 24_000, 1))!!
+ assertEquals(24_000, info.sampleRate)
+ assertEquals(1, info.channels)
+ assertEquals(16, info.bitsPerSample)
+ assertEquals(1000L, info.durationMs)
+ }
+
+ @Test
+ fun `silence matches whatever rate and channel count the speech used`() {
+ val info = PodcastAudio.wavInfo(PodcastAudio.silenceWav(300, 44_100, 2))!!
+ assertEquals(44_100, info.sampleRate)
+ assertEquals(2, info.channels)
+ assertEquals(300L, info.durationMs)
+ }
+
// ---- synthetic WAV builder ----
private fun buildWav(
diff --git a/app/src/test/java/com/gotcha/tools/PodcastToolTest.kt b/app/src/test/java/com/gotcha/tools/PodcastToolTest.kt
index 8204502..b637eae 100644
--- a/app/src/test/java/com/gotcha/tools/PodcastToolTest.kt
+++ b/app/src/test/java/com/gotcha/tools/PodcastToolTest.kt
@@ -231,6 +231,97 @@ class PodcastToolTest {
assertTrue(result.message.contains("not WAV"))
}
+ // ---- dialogue ----
+
+ private fun dialogue(
+ tool: PodcastTool,
+ lines: List<PodcastTool.DialogueLine>,
+ hostAVoice: String? = null,
+ hostBVoice: String? = null
+ ): ToolResult = runBlocking {
+ tool.synthesizeDialogue(lines, "roundtable", hostAVoice, hostBVoice)
+ }
+
+ private val twoTurns = listOf(
+ PodcastTool.DialogueLine("A", "Welcome to the show."),
+ PodcastTool.DialogueLine("B", "Great to be here.")
+ )
+
+ /** Succeeds [okCalls] times with a real (silent) WAV, then fails — lets voice capture cross turns. */
+ private fun backendFailingAfter(okCalls: Int, models: List<AudioModel> = emptyList()): FakeBackend {
+ var calls = 0
+ return FakeBackend(models = models).apply {
+ answer = {
+ if (calls++ < okCalls) {
+ Result.success(PodcastAudio.silenceWav(100, 24_000, 1))
+ } else {
+ Result.failure(IOException("stop here"))
+ }
+ }
+ }
+ }
+
+ @Test
+ fun `a dialogue line with an unknown speaker is refused before any API call`() {
+ val backend = FakeBackend()
+ val lines = twoTurns + PodcastTool.DialogueLine("C", "Who am I?")
+ val result = dialogue(tool(backend = backend), lines)
+ assertFalse(result.success)
+ assertTrue(result.message.contains("'C'"))
+ assertTrue(backend.synthesizedWith.isEmpty())
+ }
+
+ @Test
+ fun `an empty dialogue is refused before any API call`() {
+ val backend = FakeBackend()
+ val result = dialogue(tool(backend = backend), emptyList())
+ assertFalse(result.success)
+ assertTrue(backend.synthesizedWith.isEmpty())
+ }
+
+ @Test
+ fun `the hosts get distinct voices by default, host B from the model's own list`() {
+ val backend = backendFailingAfter(
+ okCalls = 1,
+ models = listOf(
+ AudioModel(
+ id = "kokoro",
+ category = ModelCategory.TTS,
+ voices = listOf(VoiceInfo(id = "af_heart"), VoiceInfo(id = "bm_george"))
+ )
+ )
+ )
+ dialogue(tool(backend = backend), twoTurns)
+ assertEquals(listOf("af_heart", "bm_george"), backend.synthesizedWith.map { it.third })
+ }
+
+ @Test
+ fun `configured host voices win over derived defaults`() {
+ val backend = backendFailingAfter(okCalls = 1)
+ val settings = apiSettings.copy(podcastHostAVoice = "am_adam", podcastHostBVoice = "bf_emma")
+ dialogue(tool(settings = settings, backend = backend), twoTurns)
+ assertEquals(listOf("am_adam", "bf_emma"), backend.synthesizedWith.map { it.third })
+ }
+
+ @Test
+ fun `explicit host voice arguments beat the configured ones`() {
+ val backend = backendFailingAfter(okCalls = 1)
+ val settings = apiSettings.copy(podcastHostAVoice = "am_adam", podcastHostBVoice = "bf_emma")
+ dialogue(tool(settings = settings, backend = backend), twoTurns, hostAVoice = "aa", hostBVoice = "bb")
+ assertEquals(listOf("aa", "bb"), backend.synthesizedWith.map { it.third })
+ }
+
+ @Test
+ fun `blank dialogue turns are dropped rather than synthesized as silence`() {
+ val backend = FakeBackend(answer = { Result.failure(IOException("capture only")) })
+ val lines = listOf(
+ PodcastTool.DialogueLine("A", "```only code```"),
+ PodcastTool.DialogueLine("B", "The real opener.")
+ )
+ dialogue(tool(backend = backend), lines)
+ assertEquals("The real opener.", backend.synthesizedWith.single().first)
+ }
+
@Test
fun `a long script reaches the API as multiple whole-sentence segments`() {
val backend = FakeBackend(answer = { Result.failure(IOException("stop after capture")) })
diff --git a/app/src/test/resources/feature-test-coverage.json b/app/src/test/resources/feature-test-coverage.json
index 116cc96..4529e8f 100644
--- a/app/src/test/resources/feature-test-coverage.json
+++ b/app/src/test/resources/feature-test-coverage.json
@@ -443,6 +443,15 @@
],
"notes": "the pure halves on the JVM — sentence-boundary script chunking (limit respected, nothing lost or reordered, oversize sentences split at word boundaries, hard cut only as a last resort) and WAV header parsing by chunk walk (real sample rate honoured rather than assumed, lying data-chunk sizes measured from what actually arrived, JSON/HTML/MP3 responses rejected) — plus every guard that runs before TTS money is spent: Android/unconfigured provider refusals with directions to Settings, blank model, scripts that sanitize to nothing or exceed the ceiling, unsupported formats, existing-output refusal, output_name slugification, and voice resolution (explicit argument beats configured voice beats the model's own default). The assembly itself is device-only — Media3 Transformer drives MediaCodec — and additionally needs a reachable TTS endpoint, so a full script-to-.m4a (and, with Termux, .mp3) run — audible joins, Files-app visibility, the .m4a fallback note — must be verified by hand"
},
+ {
+ "tool": "synthesize_podcast_dialogue",
+ "tier": "ROBOLECTRIC",
+ "tests": [
+ "com.gotcha.tools.PodcastToolTest",
+ "com.gotcha.tools.PodcastAudioTest"
+ ],
+ "notes": "shares synthesize_podcast's pipeline and its coverage, plus the dialogue-specific guards and mechanics: unknown-speaker refusal, empty-dialogue refusal, blank turns dropped after sanitising rather than synthesized as dead air, and the three-level host-voice resolution (explicit argument beats configured setting beats the first voice in the model's list that differs from host A). Silence-gap WAV generation is verified on the JVM to match the speech's own sample rate and channel count. The audible result — two distinguishable hosts with a natural pause between turns — is device-only and must be verified by hand"
+ },
{
"tool": "glob",
"tier": "ROBOLECTRIC",
diff --git a/docs/FEATURE_TEST_COVERAGE.md b/docs/FEATURE_TEST_COVERAGE.md
index 4c7c9d2..300369b 100644
--- a/docs/FEATURE_TEST_COVERAGE.md
+++ b/docs/FEATURE_TEST_COVERAGE.md
@@ -14,12 +14,12 @@ Every tool the assistant can call is listed below, together with how it is verif
| Tier | Tools | What it means |
|---|---:|---|
| `UNIT` | 24 | Plain JVM unit test — no Android framework needed. |
-| `ROBOLECTRIC` | 23 | JVM test against Robolectric's Android framework, often across several API levels. |
+| `ROBOLECTRIC` | 24 | JVM test against Robolectric's Android framework, often across several API levels. |
| `INSTRUMENTED` | 0 | Runs on a real device or emulator (`app/src/androidTest`). |
| `MANUAL_ONLY` | 64 | No automated test — verified by hand, see the checklist below. |
-| **Total** | **111** | |
+| **Total** | **112** | |
-**47 of 111** tools are covered by an automated test; the remaining 64 are manual-QA-only with a recorded reason.
+**48 of 112** tools are covered by an automated test; the remaining 64 are manual-QA-only with a recorded reason.
## Foreground tools (act on the screen)
@@ -91,6 +91,7 @@ Every tool the assistant can call is listed below, together with how it is verif
| `start_audio_recording` | `MANUAL_ONLY` | Needs real device hardware; the emulator has no faithful stand-in for this sensor/radio. |
| `stop_audio_recording` | `MANUAL_ONLY` | Needs real device hardware; the emulator has no faithful stand-in for this sensor/radio. |
| `synthesize_podcast` | `ROBOLECTRIC` | `PodcastToolTest`, `PodcastAudioTest` — the pure halves on the JVM — sentence-boundary script chunking (limit respected, nothing lost or reordered, oversize sentences split at word boundaries, hard cut only as a last resort) and WAV header parsing by chunk walk (real sample rate honoured rather than assumed, lying data-chunk sizes measured from what actually arrived, JSON/HTML/MP3 responses rejected) — plus every guard that runs before TTS money is spent: Android/unconfigured provider refusals with directions to Settings, blank model, scripts that sanitize to nothing or exceed the ceiling, unsupported formats, existing-output refusal, output_name slugification, and voice resolution (explicit argument beats configured voice beats the model's own default). The assembly itself is device-only — Media3 Transformer drives MediaCodec — and additionally needs a reachable TTS endpoint, so a full script-to-.m4a (and, with Termux, .mp3) run — audible joins, Files-app visibility, the .m4a fallback note — must be verified by hand |
+| `synthesize_podcast_dialogue` | `ROBOLECTRIC` | `PodcastToolTest`, `PodcastAudioTest` — shares synthesize_podcast's pipeline and its coverage, plus the dialogue-specific guards and mechanics: unknown-speaker refusal, empty-dialogue refusal, blank turns dropped after sanitising rather than synthesized as dead air, and the three-level host-voice resolution (explicit argument beats configured setting beats the first voice in the model's list that differs from host A). Silence-gap WAV generation is verified on the JVM to match the speech's own sample rate and channel count. The audible result — two distinguishable hosts with a natural pause between turns — is device-only and must be verified by hand |
| `take_photo` | `MANUAL_ONLY` | Needs a real camera; CameraX has no usable emulator fake for the capture callback. |
| `toggle_torch` | `MANUAL_ONLY` | Needs real device hardware; the emulator has no faithful stand-in for this sensor/radio. |
| `toggle_wifi` | `MANUAL_ONLY` | `SystemToolTest` — The permissive branch is covered by SystemToolTest, but Android 10+ makes setWifiEnabled a no-op and Robolectric's shadow honours it unconditionally, so the panel-fallback branch that actually runs on-device cannot be reproduced at that tier. |