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): script-directed pacing, with pauses inside the turn's own WAV

Durganshu Mishra4fb5b1d3fe1d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1d27288..feaf990 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,8 +8,11 @@ All notable changes to Gotcha are documented here.
for a topic, an article or your notes as a podcast and the assistant writes
the script and speaks it through your configured text-to-speech API — as a
single narrator (`synthesize_podcast`) or as two hosts in conversation with
- distinct voices and a natural pause between turns
- (`synthesize_podcast_dialogue`; pick the host voices in Settings → Speech).
+ distinct voices (`synthesize_podcast_dialogue`; pick the host voices in
+ Settings → Speech). The assistant paces the conversation as it writes it,
+ choosing the silence after each turn — a quick interjection runs straight
+ into the reply, a revelation gets a beat first — so an episode breathes
+ the way the script intended instead of ticking along on a fixed gap.
Long scripts are synthesized in segments and joined on the device, episodes
land under `Gotcha/Podcasts` as `.m4a` (or `.mp3` when Termux's ffmpeg is
available), and `share_podcast` opens the system share sheet to send one
diff --git a/app/src/main/java/com/gotcha/tools/PodcastAudio.kt b/app/src/main/java/com/gotcha/tools/PodcastAudio.kt
index c7c6197..b1dbb8e 100644
--- a/app/src/main/java/com/gotcha/tools/PodcastAudio.kt
+++ b/app/src/main/java/com/gotcha/tools/PodcastAudio.kt
@@ -127,44 +127,59 @@ 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.
+ * Returns [wav] with [durationMs] of PCM silence appended to its data
+ * chunk, both size fields patched to match.
+ *
+ * This is how a pause lands between dialogue turns: extending the turn's
+ * own audio instead of emitting a separate silence file means the joiner
+ * sees one input per turn instead of two, there is no extra re-encode
+ * boundary for a seam to appear at, and the silence matches the speech's
+ * sample rate and channel count by construction. A declared data size that
+ * was lying (streamed WAVs write 0 or -1) is replaced with the honest
+ * value while we are here.
+ *
+ * Returns null when [wav] is not a well-formed WAV — callers that already
+ * validated with [wavInfo] can treat that as "keep the original".
*/
- 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()
+ @Suppress("ReturnCount")
+ fun appendSilence(wav: ByteArray, durationMs: Long): ByteArray? {
+ if (durationMs <= 0) return wav
+ val info = wavInfo(wav) ?: return null
+
+ var offset = RIFF_HEADER_BYTES
+ var dataHeader = -1
+ while (offset + CHUNK_HEADER_BYTES <= wav.size) {
+ if (wav.ascii(offset, "data")) {
+ dataHeader = offset
+ break
+ }
+ val chunkSize = wav.leInt(offset + 4).toLong() and 0xFFFFFFFFL
+ offset += CHUNK_HEADER_BYTES + chunkSize.toInt() + (chunkSize % 2).toInt()
+ if (offset < 0) return null
+ }
+ if (dataHeader < 0) return null
+
+ val frameBytes = info.channels * (info.bitsPerSample / BITS_PER_BYTE)
+ if (frameBytes <= 0) return null
+ val extra = (durationMs * info.byteRate / MILLIS_PER_SECOND).toInt().let { it - it % frameBytes }
+ val dataEnd = dataHeader + CHUNK_HEADER_BYTES + info.dataBytes.toInt()
+
+ val out = ByteArray(wav.size + extra)
+ wav.copyInto(out, 0, 0, dataEnd)
+ // The gap itself is already zeros; only the region after it needs copying.
+ wav.copyInto(out, dataEnd + extra, dataEnd, wav.size)
+ out.patchLe32(dataHeader + 4, (info.dataBytes + extra).toInt())
+ out.patchLe32(4, out.size - CHUNK_HEADER_BYTES)
+ return out
}
+ private fun ByteArray.patchLe32(offset: Int, value: Int) {
+ repeat(4) { this[offset + it] = ((value shr (BITS_PER_BYTE * it)) and 0xFF).toByte() }
+ }
+
+ private const val BITS_PER_BYTE = 8
+
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 c462631..3a95746 100644
--- a/app/src/main/java/com/gotcha/tools/PodcastTool.kt
+++ b/app/src/main/java/com/gotcha/tools/PodcastTool.kt
@@ -60,8 +60,12 @@ 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)
+ /**
+ * One turn of a dialogue script, as the model writes it. [pauseMs] is the
+ * script's pacing direction — the silence after this turn — null meaning
+ * "use the episode default".
+ */
+ data class DialogueLine(val speaker: String, val text: String, val pauseMs: Long? = null)
private val resolver = FileResolver(context)
@@ -85,11 +89,25 @@ class PodcastTool(
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.
+ * Breathing room between dialogue turns when neither the call's
+ * `gap_ms` nor the line's `pause_ms` says otherwise. Long enough to
+ * read as a speaker change, short enough not to read as dead air.
*/
const val DIALOGUE_GAP_MS = 300L
+ /** Ceiling on any single pause — past this a "beat" is just dead air, or a hallucinated number. */
+ const val MAX_TURN_PAUSE_MS = 2_000L
+
+ /**
+ * The pause that actually lands after a turn: the line's own request
+ * if it carried one, the episode default otherwise, clamped either
+ * way. A `pause_ms` the dispatcher could not read arrives here as
+ * null, which is what makes the default the fallback rather than an
+ * error.
+ */
+ fun resolvePause(requested: Long?, default: Long): Long =
+ (requested ?: default).coerceIn(0L, MAX_TURN_PAUSE_MS)
+
private const val TTS_TIMEOUT_SECONDS = 120L
private const val FORMAT_M4A = "m4a"
private const val FORMAT_MP3 = "mp3"
@@ -123,14 +141,17 @@ class PodcastTool(
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.
+ * One spoken turn: its segments (an over-long turn chunks into several)
+ * and the silence appended after its last segment. The pause lives on the
+ * turn, never between a turn's own chunks — a pause inside a sentence
+ * would be a stall, not a beat.
*/
+ private data class Turn(val segments: List<SpeechSegment>, val pauseAfterMs: Long)
+
+ /** Everything one synthesis run carries between its stages. */
private data class SynthesisJob(
val backend: TtsBackend,
- val groups: List<List<SpeechSegment>>,
- val gapMs: Long,
+ val turns: List<Turn>,
val tempDir: File,
val destination: File,
val wantMp3: Boolean,
@@ -168,8 +189,7 @@ class PodcastTool(
.map { SpeechSegment(it, resolvedModel, resolvedVoice) }
return runJob(
backend = backend,
- groups = listOf(segments),
- gapMs = 0L,
+ turns = listOf(Turn(segments, pauseAfterMs = 0L)),
outputName = outputName,
requestedFormat = requestedFormat,
overwrite = overwrite,
@@ -186,6 +206,7 @@ class PodcastTool(
hostBVoice: String? = null,
hostAModel: String? = null,
hostBModel: String? = null,
+ gapMs: Long? = null,
format: String? = null,
overwrite: Boolean = false
): ToolResult {
@@ -218,14 +239,18 @@ class PodcastTool(
""
}
- val groups = turns.map { turn ->
+ val episodeGap = resolvePause(gapMs, DIALOGUE_GAP_MS)
+ val spoken = turns.mapIndexed { index, 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) }
+ Turn(
+ segments = PodcastAudio.chunk(turn.text, MAX_CHUNK_CHARS).map { SpeechSegment(it, model, voice) },
+ // Nothing follows the last turn, so a pause there is only trailing silence.
+ pauseAfterMs = if (index == turns.lastIndex) 0L else resolvePause(turn.pauseMs, episodeGap)
+ )
}
return runJob(
backend = backend,
- groups = groups,
- gapMs = DIALOGUE_GAP_MS,
+ turns = spoken,
outputName = outputName,
requestedFormat = requestedFormat,
overwrite = overwrite,
@@ -239,8 +264,7 @@ class PodcastTool(
@Suppress("ReturnCount", "LongParameterList")
private suspend fun runJob(
backend: TtsBackend,
- groups: List<List<SpeechSegment>>,
- gapMs: Long,
+ turns: List<Turn>,
outputName: String,
requestedFormat: String,
overwrite: Boolean,
@@ -264,7 +288,7 @@ class PodcastTool(
return try {
produce(
SynthesisJob(
- backend = backend, groups = groups, gapMs = gapMs, tempDir = tempDir,
+ backend = backend, turns = turns, tempDir = tempDir,
destination = destination, wantMp3 = wantMp3, baseName = baseName,
overwrite = overwrite, notes = notes + degradeNote, voiceLabel = voiceLabel
)
@@ -277,14 +301,12 @@ class PodcastTool(
@Suppress("ReturnCount")
private suspend fun produce(job: SynthesisJob): ToolResult {
job.tempDir.mkdirs()
- val totalSegments = job.groups.sumOf { it.size }
+ val totalSegments = job.turns.sumOf { it.segments.size }
val files = mutableListOf<File>()
- val silenceByFormat = mutableMapOf<Pair<Int, Int>, File>()
var totalMs = 0L
var index = 0
- var lastWav: PodcastAudio.WavInfo? = null
- for ((groupIndex, group) in job.groups.withIndex()) {
- for (segment in group) {
+ for (turn in job.turns) {
+ for ((positionInTurn, segment) in turn.segments.withIndex()) {
coroutineContext.ensureActive()
index++
val bytes = job.backend.synthesize(segment.text, segment.model, segment.voice).getOrElse { e ->
@@ -298,19 +320,14 @@ class PodcastTool(
"The model name or voice may be wrong for this provider — check them against the " +
"provider's model list."
)
- totalMs += info.durationMs
+ // The turn's pause rides on its final segment, so the joiner sees
+ // one input per segment and no seam where the silence begins.
+ val lastOfTurn = positionInTurn == turn.segments.lastIndex
+ val pauseMs = if (lastOfTurn) turn.pauseAfterMs else 0L
+ val audio = if (pauseMs > 0) PodcastAudio.appendSilence(bytes, pauseMs) ?: bytes else bytes
+ totalMs += info.durationMs + if (audio !== bytes) pauseMs else 0L
if (totalMs > MAX_TOTAL_DURATION_MS) return audioTooLong()
- files += File(job.tempDir, "segment_%03d.wav".format(index)).apply { writeBytes(bytes) }
- lastWav = info
- }
- 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
+ files += File(job.tempDir, "segment_%03d.wav".format(index)).apply { writeBytes(audio) }
}
}
diff --git a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
index fce96ab..0869bf1 100644
--- a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
@@ -1515,8 +1515,10 @@ object ToolDefinitions {
"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 " +
+ "and defaulting to two different voices from the model's own list). You also direct the pacing: " +
+ "each turn may carry a pause_ms for the silence after it — a quick interjection wants less than " +
+ "a beat before a revelation — and gap_ms sets the episode's default. 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 {
@@ -1526,7 +1528,8 @@ object ToolDefinitions {
put(
"description",
"The dialogue in order. Each item is one turn: " +
- "{\"speaker\": \"A\" or \"B\", \"text\": \"the words to speak\"}."
+ "{\"speaker\": \"A\" or \"B\", \"text\": \"the words to speak\", " +
+ "\"pause_ms\": optional pacing}."
)
putJsonObject("items") {
put("type", "object")
@@ -1539,6 +1542,17 @@ object ToolDefinitions {
put("type", "string")
put("description", "What this host says, spoken verbatim. Plain prose only.")
}
+ putJsonObject("pause_ms") {
+ put("type", "integer")
+ put(
+ "description",
+ "Silence AFTER this turn, in milliseconds — pacing you direct like a " +
+ "stage direction. Roughly: 150-250 for quick back-and-forth, 300 " +
+ "for a normal hand-off, 500-800 to let a point land or mark a topic " +
+ "change. Omit it and the turn uses gap_ms. Clamped to 0-2000, and " +
+ "ignored on the final turn, where it would only be trailing silence."
+ )
+ }
}
putJsonArray("required") {
add("speaker")
@@ -1546,6 +1560,14 @@ object ToolDefinitions {
}
}
}
+ putJsonObject("gap_ms") {
+ put("type", "integer")
+ put(
+ "description",
+ "Default silence between turns for this episode, in milliseconds (0-2000, " +
+ "default 300). Individual lines override it with their own pause_ms."
+ )
+ }
putJsonObject("output_name") {
put("type", "string")
put(
diff --git a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
index f18bb5d..6cbb9f7 100644
--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
@@ -17,6 +17,7 @@ import kotlinx.serialization.json.doubleOrNull
import kotlinx.serialization.json.intOrNull
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonPrimitive
+import kotlinx.serialization.json.longOrNull
/**
* Single dispatch point for all tool side effects. Validates args, checks
@@ -266,6 +267,7 @@ class ToolExecutor(
hostBVoice = args.requireString("host_b_voice"),
hostAModel = args.requireString("host_a_model"),
hostBModel = args.requireString("host_b_model"),
+ gapMs = args.requireInt("gap_ms")?.toLong(),
format = args.requireString("format"),
overwrite = args.requireBoolean("overwrite") ?: false
)
@@ -674,7 +676,12 @@ 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. */
+ /**
+ * Null on a malformed entry rather than dropping it — a silently skipped
+ * turn is a mangled episode. `pause_ms` is the exception: it is pacing
+ * advice, so an unreadable one falls back to the episode default instead
+ * of failing a script that is otherwise fine.
+ */
private fun parseDialogueLines(element: JsonElement?): List<PodcastTool.DialogueLine>? {
val array = element as? JsonArray ?: return null
if (array.isEmpty()) return null
@@ -682,7 +689,8 @@ class ToolExecutor(
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)
+ val pause = (obj["pause_ms"] as? JsonPrimitive)?.let { it.longOrNull ?: it.content.trim().toLongOrNull() }
+ PodcastTool.DialogueLine(speaker, text, pause)
}
}
diff --git a/app/src/test/java/com/gotcha/tools/PodcastAudioTest.kt b/app/src/test/java/com/gotcha/tools/PodcastAudioTest.kt
index c2874d4..3d29fd9 100644
--- a/app/src/test/java/com/gotcha/tools/PodcastAudioTest.kt
+++ b/app/src/test/java/com/gotcha/tools/PodcastAudioTest.kt
@@ -1,5 +1,6 @@
package com.gotcha.tools
+import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
@@ -119,34 +120,105 @@ class PodcastAudioTest {
assertNull(PodcastAudio.wavInfo(byteArrayOf(0xFF.toByte(), 0xFB.toByte()) + ByteArray(100)))
}
- // ---- silence generation ----
+ // ---- appending silence ----
@Test
- fun `generated silence is a valid WAV of the requested format and length`() {
- val info = PodcastAudio.wavInfo(PodcastAudio.silenceWav(1000, 24_000, 1))!!
+ fun `appending silence extends the duration by exactly that much`() {
+ val speech = buildWav(sampleRate = 24_000, channels = 1, bitsPerSample = 16, dataBytes = 48_000)
+ val padded = PodcastAudio.appendSilence(speech, 300)!!
+ val info = PodcastAudio.wavInfo(padded)!!
+ assertEquals(1300L, info.durationMs)
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)
+ fun `the pause inherits the speech's own rate and channel count`() {
+ // 500ms of 44.1kHz stereo is 88200 bytes, not the 24kHz-mono 24000.
+ val speech = buildWav(sampleRate = 44_100, channels = 2, bitsPerSample = 16, dataBytes = 176_400)
+ val padded = PodcastAudio.appendSilence(speech, 500)!!
+ assertEquals(speech.size + 88_200, padded.size)
+ assertEquals(1500L, PodcastAudio.wavInfo(padded)!!.durationMs)
+ }
+
+ @Test
+ fun `the original audio is preserved byte for byte ahead of the pause`() {
+ val speech = buildWav(
+ sampleRate = 24_000,
+ channels = 1,
+ bitsPerSample = 16,
+ dataBytes = 4_800,
+ dataFill = { (it % 251).toByte() }
+ )
+ val padded = PodcastAudio.appendSilence(speech, 100)!!
+ val spoken = PodcastAudio.wavInfo(speech)!!.dataBytes.toInt()
+ val dataStart = speech.size - spoken
+ assertArrayEquals(
+ speech.copyOfRange(dataStart, speech.size),
+ padded.copyOfRange(dataStart, dataStart + spoken)
+ )
+ }
+
+ @Test
+ fun `the appended region is actual silence`() {
+ val speech = buildWav(
+ sampleRate = 24_000,
+ channels = 1,
+ bitsPerSample = 16,
+ dataBytes = 4_800,
+ dataFill = { 0x7F }
+ )
+ val padded = PodcastAudio.appendSilence(speech, 100)!!
+ val tail = padded.copyOfRange(speech.size, padded.size)
+ assertTrue("nothing was appended", tail.isNotEmpty())
+ assertTrue("appended region is not silent", tail.all { it == 0.toByte() })
+ }
+
+ @Test
+ fun `a zero or negative pause returns the audio untouched`() {
+ val speech = buildWav(sampleRate = 24_000, channels = 1, bitsPerSample = 16, dataBytes = 4_800)
+ assertArrayEquals(speech, PodcastAudio.appendSilence(speech, 0))
+ assertArrayEquals(speech, PodcastAudio.appendSilence(speech, -100))
+ }
+
+ @Test
+ fun `appending to something that is not a WAV reports failure instead of corrupting it`() {
+ assertNull(PodcastAudio.appendSilence("{\"error\":\"nope\"}".toByteArray(), 300))
+ assertNull(PodcastAudio.appendSilence(ByteArray(8), 300))
+ }
+
+ @Test
+ fun `a padded WAV survives a second round of padding`() {
+ // Proves the patched size fields are honest enough to parse again.
+ val speech = buildWav(sampleRate = 24_000, channels = 1, bitsPerSample = 16, dataBytes = 24_000)
+ val once = PodcastAudio.appendSilence(speech, 200)!!
+ val twice = PodcastAudio.appendSilence(once, 300)!!
+ assertEquals(1000L, PodcastAudio.wavInfo(twice)!!.durationMs)
+ }
+
+ @Test
+ fun `padding walks past a leading chunk to find the real data chunk`() {
+ val speech = buildWav(
+ sampleRate = 24_000,
+ channels = 1,
+ bitsPerSample = 16,
+ dataBytes = 24_000,
+ leadingJunkChunk = true
+ )
+ assertEquals(700L, PodcastAudio.wavInfo(PodcastAudio.appendSilence(speech, 200)!!)!!.durationMs)
}
// ---- synthetic WAV builder ----
+ @Suppress("LongParameterList")
private fun buildWav(
sampleRate: Int,
channels: Int,
bitsPerSample: Int,
dataBytes: Int,
leadingJunkChunk: Boolean = false,
- declaredDataSize: Int = dataBytes
+ declaredDataSize: Int = dataBytes,
+ dataFill: ((Int) -> Byte)? = null
): ByteArray {
val out = ByteArrayOutputStream()
fun ascii(s: String) = out.write(s.toByteArray(Charsets.US_ASCII))
@@ -172,7 +244,7 @@ class PodcastAudioTest {
le16(bitsPerSample)
ascii("data")
le32(declaredDataSize)
- out.write(ByteArray(dataBytes))
+ out.write(if (dataFill == null) ByteArray(dataBytes) else ByteArray(dataBytes) { dataFill(it) })
return out.toByteArray()
}
}
diff --git a/app/src/test/java/com/gotcha/tools/PodcastToolTest.kt b/app/src/test/java/com/gotcha/tools/PodcastToolTest.kt
index 8123fdf..adfc86d 100644
--- a/app/src/test/java/com/gotcha/tools/PodcastToolTest.kt
+++ b/app/src/test/java/com/gotcha/tools/PodcastToolTest.kt
@@ -237,9 +237,10 @@ class PodcastToolTest {
tool: PodcastTool,
lines: List<PodcastTool.DialogueLine>,
hostAVoice: String? = null,
- hostBVoice: String? = null
+ hostBVoice: String? = null,
+ gapMs: Long? = null
): ToolResult = runBlocking {
- tool.synthesizeDialogue(lines, "roundtable", hostAVoice, hostBVoice)
+ tool.synthesizeDialogue(lines, "roundtable", hostAVoice, hostBVoice, gapMs = gapMs)
}
private val twoTurns = listOf(
@@ -247,16 +248,36 @@ class PodcastToolTest {
PodcastTool.DialogueLine("B", "Great to be here.")
)
- /** Succeeds [okCalls] times with a real (silent) WAV, then fails — lets voice capture cross turns. */
+ /** 100ms of 24kHz mono PCM16 — a valid WAV for the fake backend to return. */
+ private fun fakeWav(): ByteArray {
+ val dataBytes = 4_800
+ val out = java.io.ByteArrayOutputStream()
+ fun ascii(s: String) = s.forEach { out.write(it.code) }
+ fun le32(v: Int) = repeat(4) { out.write((v shr (8 * it)) and 0xFF) }
+ fun le16(v: Int) = repeat(2) { out.write((v shr (8 * it)) and 0xFF) }
+ ascii("RIFF")
+ le32(36 + dataBytes)
+ ascii("WAVE")
+ ascii("fmt ")
+ le32(16)
+ le16(1)
+ le16(1)
+ le32(24_000)
+ le32(48_000)
+ le16(2)
+ le16(16)
+ ascii("data")
+ le32(dataBytes)
+ out.write(ByteArray(dataBytes))
+ return out.toByteArray()
+ }
+
+ /** Succeeds [okCalls] times with a real 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"))
- }
+ if (calls++ < okCalls) Result.success(fakeWav()) else Result.failure(IOException("stop here"))
}
}
}
@@ -311,6 +332,51 @@ class PodcastToolTest {
assertEquals(listOf("aa", "bb"), backend.synthesizedWith.map { it.third })
}
+ // ---- pacing ----
+
+ @Test
+ fun `a line without pause_ms falls back to the episode default`() {
+ assertEquals(
+ PodcastTool.DIALOGUE_GAP_MS,
+ PodcastTool.resolvePause(requested = null, default = PodcastTool.DIALOGUE_GAP_MS)
+ )
+ }
+
+ @Test
+ fun `a line's own pause_ms overrides the episode default`() {
+ assertEquals(750L, PodcastTool.resolvePause(requested = 750L, default = PodcastTool.DIALOGUE_GAP_MS))
+ }
+
+ @Test
+ fun `a zero pause is honoured, not treated as unset`() {
+ // The difference that matters: "run these turns together" must not silently become 300ms.
+ assertEquals(0L, PodcastTool.resolvePause(requested = 0L, default = PodcastTool.DIALOGUE_GAP_MS))
+ }
+
+ @Test
+ fun `an absurd or negative pause is clamped rather than obeyed`() {
+ assertEquals(PodcastTool.MAX_TURN_PAUSE_MS, PodcastTool.resolvePause(999_999L, PodcastTool.DIALOGUE_GAP_MS))
+ assertEquals(0L, PodcastTool.resolvePause(-5_000L, PodcastTool.DIALOGUE_GAP_MS))
+ }
+
+ @Test
+ fun `a hallucinated gap_ms cannot stretch the episode through the lines that inherit it`() {
+ val episodeGap = PodcastTool.resolvePause(60_000L, PodcastTool.DIALOGUE_GAP_MS)
+ assertEquals(PodcastTool.MAX_TURN_PAUSE_MS, episodeGap)
+ assertEquals(PodcastTool.MAX_TURN_PAUSE_MS, PodcastTool.resolvePause(null, episodeGap))
+ }
+
+ @Test
+ fun `a dialogue with custom pacing still reaches the API with its text intact`() {
+ val backend = backendFailingAfter(okCalls = 1)
+ val paced = listOf(
+ PodcastTool.DialogueLine("A", "So here's the thing.", pauseMs = 800),
+ PodcastTool.DialogueLine("B", "Go on.", pauseMs = 150)
+ )
+ dialogue(tool(backend = backend), paced, gapMs = 250L)
+ assertEquals(listOf("So here's the thing.", "Go on."), backend.synthesizedWith.map { it.first })
+ }
+
@Test
fun `blank dialogue turns are dropped rather than synthesized as silence`() {
val backend = FakeBackend(answer = { Result.failure(IOException("capture only")) })
diff --git a/app/src/test/resources/feature-test-coverage.json b/app/src/test/resources/feature-test-coverage.json
index 0909509..0e1b6ea 100644
--- a/app/src/test/resources/feature-test-coverage.json
+++ b/app/src/test/resources/feature-test-coverage.json
@@ -450,7 +450,7 @@
"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"
+ "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). Pacing is covered on both halves: pause resolution (a line's pause_ms beats gap_ms beats the 300ms default, zero honoured as zero rather than treated as unset, absurd or negative values clamped) and the silence append itself (duration grows by exactly the requested pause, the pause inherits the speech's own sample rate and channel count, the spoken bytes survive untouched, the appended region is genuinely silent, and a padded WAV re-parses so it can be padded again). The audible result — two distinguishable hosts and whether the chosen pauses actually sound like conversation — is device-only and must be verified by hand"
},
{
"tool": "share_podcast",
diff --git a/docs/FEATURE_TEST_COVERAGE.md b/docs/FEATURE_TEST_COVERAGE.md
index 648d6f5..14eb859 100644
--- a/docs/FEATURE_TEST_COVERAGE.md
+++ b/docs/FEATURE_TEST_COVERAGE.md
@@ -92,7 +92,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 |
+| `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). Pacing is covered on both halves: pause resolution (a line's pause_ms beats gap_ms beats the 300ms default, zero honoured as zero rather than treated as unset, absurd or negative values clamped) and the silence append itself (duration grows by exactly the requested pause, the pause inherits the speech's own sample rate and channel count, the spoken bytes survive untouched, the appended region is genuinely silent, and a padded WAV re-parses so it can be padded again). The audible result — two distinguishable hosts and whether the chosen pauses actually sound like conversation — 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. |