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(convert): ffmpeg command construction for on-device format conversion

Durganshu46c2f33549ad
diff --git a/app/src/main/java/com/gotcha/tools/FfmpegCommand.kt b/app/src/main/java/com/gotcha/tools/FfmpegCommand.kt
new file mode 100644
index 0000000..ff49762
--- /dev/null
+++ b/app/src/main/java/com/gotcha/tools/FfmpegCommand.kt
@@ -0,0 +1,158 @@
+package com.gotcha.tools
+
+import java.util.Locale
+
+/**
+ * Builds the `ffmpeg` command lines that [MediaConvertTool] hands to Termux.
+ *
+ * Split out of the tool and free of Android APIs for the same reason
+ * [MediaTimeSpec] is: this is where the bugs would be, and none of it needs a
+ * device to test. Two parts carry real risk.
+ *
+ * First, quoting. [TermuxTool] runs its argument through `sh -c`, so every path
+ * that reaches here is shell source. A file called `my song.mp3` would split into
+ * two arguments unquoted, and one called `a';rm -rf ~;'.mp3` would do rather
+ * worse. [shellQuote] is therefore applied to every interpolated value without
+ * exception, and the format arguments themselves are drawn from a fixed table
+ * rather than from anything the model wrote.
+ *
+ * Second, path translation. Gotcha addresses shared storage as
+ * `/storage/emulated/0/…`, but inside Termux that path must be written
+ * `/sdcard/…` — see the bundled `termux_filesystem` skill. Getting this wrong
+ * produces a "No such file or directory" that looks like a missing file rather
+ * than a wrong prefix.
+ */
+object FfmpegCommand {
+
+ /** Android's canonical shared-storage root, as Gotcha's [FileResolver] reports it. */
+ const val SHARED_STORAGE_ROOT = "/storage/emulated/0"
+
+ /** The same tree as Termux must address it. */
+ const val TERMUX_STORAGE_ROOT = "/sdcard"
+
+ /** Default bitrate for the lossy targets that do not name their own. */
+ private const val DEFAULT_BITRATE = "192k"
+
+ /**
+ * One conversion target: the codec arguments that produce it.
+ *
+ * @param codecArgs fixed arguments, never interpolated from model input.
+ * @param bitrate default `-b:a` value, or null for the lossless targets where
+ * a bitrate is meaningless and ffmpeg would reject or ignore it.
+ */
+ data class Target(
+ val extension: String,
+ val codecArgs: List<String>,
+ val bitrate: String?,
+ val description: String
+ ) {
+ val isLossless: Boolean get() = bitrate == null
+ }
+
+ /**
+ * Audio targets, keyed by output extension.
+ *
+ * MP3 is the point of this tool's existence: Android ships no MP3 encoder and
+ * its muxer cannot write one, so `media_edit` can never produce it, while
+ * Termux's ffmpeg carries libmp3lame. The rest come almost free once the
+ * plumbing exists.
+ */
+ val AUDIO_TARGETS: Map<String, Target> = listOf(
+ Target("mp3", listOf("-c:a", "libmp3lame"), DEFAULT_BITRATE, "MP3, the most widely playable lossy format"),
+ Target("m4a", listOf("-c:a", "aac"), DEFAULT_BITRATE, "AAC in an MP4 container"),
+ Target("aac", listOf("-c:a", "aac"), DEFAULT_BITRATE, "raw AAC stream"),
+ Target("ogg", listOf("-c:a", "libvorbis"), DEFAULT_BITRATE, "Vorbis in an Ogg container"),
+ Target("opus", listOf("-c:a", "libopus"), "128k", "Opus, the best quality per byte at low bitrates"),
+ Target("wav", listOf("-c:a", "pcm_s16le"), null, "uncompressed PCM, large but lossless"),
+ Target("flac", listOf("-c:a", "flac"), null, "FLAC, compressed but lossless")
+ ).associateBy { it.extension }
+
+ /** Bitrates the model may ask for: "192k", "320k", or a bare kbps number. */
+ private val BITRATE_FORM = Regex("^(\\d{1,4})k?$", RegexOption.IGNORE_CASE)
+
+ /**
+ * Quotes [value] for `sh`.
+ *
+ * Single quotes suppress every form of shell expansion, so the only character
+ * needing care is the single quote itself: the string is closed, an escaped
+ * quote is emitted, and the string reopened. This is the standard POSIX idiom
+ * and handles spaces, newlines, `$`, backticks, `;` and `&` alike.
+ */
+ fun shellQuote(value: String): String = "'" + value.replace("'", "'\\''") + "'"
+
+ /**
+ * Rewrites a Gotcha shared-storage path into the form Termux must use.
+ * Anything outside shared storage is returned unchanged — [MediaConvertTool]
+ * refuses those separately, with an explanation Termux itself cannot give.
+ */
+ fun termuxPath(canonicalPath: String): String = when {
+ canonicalPath == SHARED_STORAGE_ROOT -> TERMUX_STORAGE_ROOT
+ canonicalPath.startsWith("$SHARED_STORAGE_ROOT/") ->
+ TERMUX_STORAGE_ROOT + canonicalPath.removePrefix(SHARED_STORAGE_ROOT)
+ else -> canonicalPath
+ }
+
+ /** True when [canonicalPath] is somewhere Termux can reach at all. */
+ fun isReachableFromTermux(canonicalPath: String): Boolean =
+ canonicalPath == SHARED_STORAGE_ROOT || canonicalPath.startsWith("$SHARED_STORAGE_ROOT/")
+
+ /**
+ * Normalises a requested bitrate to ffmpeg's spelling, or null when it is not
+ * a bitrate at all. Validated rather than passed through: it lands in a shell
+ * command, and a quoted-but-nonsense value would fail deep inside ffmpeg with
+ * a message the model cannot act on.
+ */
+ fun normaliseBitrate(bitrate: String?): String? {
+ val trimmed = bitrate?.trim().orEmpty()
+ if (trimmed.isEmpty()) return null
+ val match = BITRATE_FORM.matchEntire(trimmed) ?: return null
+ val kbps = match.groupValues[1].toIntOrNull() ?: return null
+ if (kbps !in MIN_BITRATE_KBPS..MAX_BITRATE_KBPS) return null
+ return "${kbps}k"
+ }
+
+ const val MIN_BITRATE_KBPS = 8
+ const val MAX_BITRATE_KBPS = 2000
+
+ /**
+ * The audio-conversion command.
+ *
+ * `-nostdin` because a headless ffmpeg that reads stdin blocks until Gotcha's
+ * timeout and reports a hang rather than the prompt it is stuck on. `-y`
+ * because the caller has already made the overwrite decision, and an
+ * interactive "overwrite?" prompt would do the same. `-loglevel error` keeps
+ * the result inside Termux's ~100KB output cap. `-vn` drops any video track,
+ * without which ffmpeg tries to carry cover art into formats that cannot hold
+ * it.
+ */
+ fun buildAudioConversion(
+ inputCanonical: String,
+ outputCanonical: String,
+ target: Target,
+ bitrate: String?
+ ): String {
+ val args = mutableListOf("ffmpeg", "-nostdin", "-loglevel", "error", "-y")
+ args += listOf("-i", shellQuote(termuxPath(inputCanonical)))
+ args += "-vn"
+ args += target.codecArgs
+ val effective = if (target.isLossless) null else bitrate ?: target.bitrate
+ effective?.let { args += listOf("-b:a", it) }
+ args += shellQuote(termuxPath(outputCanonical))
+ return args.joinToString(" ")
+ }
+
+ /**
+ * Probes for ffmpeg without running a conversion. `command -v` is a shell
+ * builtin, so this costs nothing and works whether ffmpeg is a binary or a
+ * shell function.
+ */
+ const val PROBE_COMMAND = "command -v ffmpeg"
+
+ /** Lists the supported targets for an error message, longest-lived first. */
+ fun describeAudioTargets(): String =
+ AUDIO_TARGETS.values.joinToString(", ") { ".${it.extension}" }
+
+ /** Looks up a target by output extension, case-insensitively. */
+ fun audioTargetFor(extension: String): Target? =
+ AUDIO_TARGETS[extension.lowercase(Locale.ROOT)]
+}
diff --git a/app/src/test/java/com/gotcha/tools/FfmpegCommandTest.kt b/app/src/test/java/com/gotcha/tools/FfmpegCommandTest.kt
new file mode 100644
index 0000000..4c009c8
--- /dev/null
+++ b/app/src/test/java/com/gotcha/tools/FfmpegCommandTest.kt
@@ -0,0 +1,191 @@
+package com.gotcha.tools
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/**
+ * Command construction for `media_convert`. Pure JVM: [FfmpegCommand] touches no
+ * Android API, and this is where the consequences of a mistake are worst — the
+ * output is shell source handed to `sh -c` inside Termux, so a quoting hole is a
+ * command-injection hole, and a wrong path prefix is an error message that
+ * blames a missing file.
+ */
+class FfmpegCommandTest {
+
+ // ---- shell quoting: the security-relevant half ----
+
+ @Test
+ fun `ordinary paths are wrapped in single quotes`() {
+ assertEquals("'/sdcard/Music/song.mp3'", FfmpegCommand.shellQuote("/sdcard/Music/song.mp3"))
+ }
+
+ @Test
+ fun `spaces survive quoting as one argument`() {
+ assertEquals("'/sdcard/My Music/a song.m4a'", FfmpegCommand.shellQuote("/sdcard/My Music/a song.m4a"))
+ }
+
+ @Test
+ fun `an embedded single quote cannot break out of the string`() {
+ // The POSIX idiom: close, escaped quote, reopen.
+ assertEquals("""'it'\''s.mp3'""", FfmpegCommand.shellQuote("it's.mp3"))
+ }
+
+ @Test
+ fun `shell metacharacters are inert once quoted`() {
+ listOf(
+ "a;rm -rf ~;.mp3",
+ "\$(reboot).mp3",
+ "`id`.mp3",
+ "a&&b.mp3",
+ "a|b.mp3",
+ "a\nb.mp3",
+ "*.mp3",
+ "~/secret.mp3"
+ ).forEach { hostile ->
+ val quoted = FfmpegCommand.shellQuote(hostile)
+ assertTrue(hostile, quoted.startsWith("'") && quoted.endsWith("'"))
+ // Nothing between the outer quotes may terminate the string except the
+ // escaped form, which is the only way a bare quote is allowed to appear.
+ val inner = quoted.substring(1, quoted.length - 1)
+ assertFalse(hostile, inner.replace("""'\''""", "").contains("'"))
+ }
+ }
+
+ @Test
+ fun `a filename that is only quotes still round-trips`() {
+ assertEquals("""''\'''\'''""", FfmpegCommand.shellQuote("''"))
+ }
+
+ // ---- path translation ----
+
+ @Test
+ fun `shared storage is rewritten to the sdcard prefix Termux needs`() {
+ assertEquals("/sdcard/Music/a.m4a", FfmpegCommand.termuxPath("/storage/emulated/0/Music/a.m4a"))
+ assertEquals("/sdcard", FfmpegCommand.termuxPath("/storage/emulated/0"))
+ }
+
+ @Test
+ fun `a path merely starting with the same characters is not rewritten`() {
+ // "/storage/emulated/0extra" is a different tree; a prefix match without
+ // the separator would silently corrupt it.
+ assertEquals("/storage/emulated/0extra/a.mp3", FfmpegCommand.termuxPath("/storage/emulated/0extra/a.mp3"))
+ }
+
+ @Test
+ fun `paths outside shared storage are left alone`() {
+ assertEquals("/data/data/com.gotcha/files/a.m4a", FfmpegCommand.termuxPath("/data/data/com.gotcha/files/a.m4a"))
+ }
+
+ @Test
+ fun `reachability follows the same boundary as translation`() {
+ assertTrue(FfmpegCommand.isReachableFromTermux("/storage/emulated/0/Download/a.m4a"))
+ assertTrue(FfmpegCommand.isReachableFromTermux("/storage/emulated/0"))
+ assertFalse(FfmpegCommand.isReachableFromTermux("/data/data/com.gotcha/files/a.m4a"))
+ assertFalse(FfmpegCommand.isReachableFromTermux("/storage/emulated/0extra/a.mp3"))
+ }
+
+ // ---- bitrate validation ----
+
+ @Test
+ fun `bitrates are accepted with or without the k suffix`() {
+ assertEquals("192k", FfmpegCommand.normaliseBitrate("192k"))
+ assertEquals("192k", FfmpegCommand.normaliseBitrate("192"))
+ assertEquals("320k", FfmpegCommand.normaliseBitrate(" 320K "))
+ }
+
+ @Test
+ fun `a non-bitrate is rejected rather than quoted and passed on`() {
+ listOf("high", "192kbps", "-192", "1e3", "192k; rm -rf ~", "").forEach {
+ assertNull(it, FfmpegCommand.normaliseBitrate(it))
+ }
+ assertNull(FfmpegCommand.normaliseBitrate(null))
+ }
+
+ @Test
+ fun `implausible bitrates are rejected at both ends`() {
+ assertNull(FfmpegCommand.normaliseBitrate("0"))
+ assertNull(FfmpegCommand.normaliseBitrate("9999"))
+ }
+
+ // ---- command assembly ----
+
+ private fun audio(
+ input: String = "/storage/emulated/0/Music/in.m4a",
+ output: String = "/storage/emulated/0/Music/out.mp3",
+ extension: String = "mp3",
+ bitrate: String? = null
+ ): String = FfmpegCommand.buildAudioConversion(
+ input,
+ output,
+ FfmpegCommand.audioTargetFor(extension)!!,
+ bitrate
+ )
+
+ @Test
+ fun `the mp3 conversion names lame and a default bitrate`() {
+ val command = audio()
+ assertEquals(
+ "ffmpeg -nostdin -loglevel error -y -i '/sdcard/Music/in.m4a' -vn " +
+ "-c:a libmp3lame -b:a 192k '/sdcard/Music/out.mp3'",
+ command
+ )
+ }
+
+ @Test
+ fun `an explicit bitrate overrides the target default`() {
+ assertTrue(audio(bitrate = "320k").contains("-b:a 320k"))
+ }
+
+ @Test
+ fun `lossless targets carry no bitrate even when one is supplied`() {
+ listOf("wav", "flac").forEach { ext ->
+ val command = audio(output = "/storage/emulated/0/Music/out.$ext", extension = ext, bitrate = "320k")
+ assertFalse(ext, command.contains("-b:a"))
+ }
+ }
+
+ @Test
+ fun `every audio target produces a runnable command`() {
+ FfmpegCommand.AUDIO_TARGETS.keys.forEach { ext ->
+ val command = audio(output = "/storage/emulated/0/Music/out.$ext", extension = ext)
+ assertTrue(ext, command.startsWith("ffmpeg -nostdin -loglevel error -y -i "))
+ assertTrue(ext, command.endsWith("'/sdcard/Music/out.$ext'"))
+ assertTrue(ext, command.contains("-c:a"))
+ }
+ }
+
+ @Test
+ fun `non-interactive flags are always present`() {
+ // Without -nostdin and -y a headless ffmpeg blocks on a prompt until the
+ // Termux timeout, and reports a hang rather than the question it asked.
+ val command = audio()
+ assertTrue(command.contains("-nostdin"))
+ assertTrue(command.contains("-y"))
+ assertTrue(command.contains("-loglevel error"))
+ }
+
+ @Test
+ fun `video is dropped so cover art cannot block the muxer`() {
+ assertTrue(audio().contains("-vn"))
+ }
+
+ @Test
+ fun `hostile filenames stay inert in the assembled command`() {
+ val command = audio(input = "/storage/emulated/0/Music/a';reboot;'.m4a")
+ assertTrue(command.contains("""'/sdcard/Music/a'\'';reboot;'\''.m4a'"""))
+ }
+
+ @Test
+ fun `target lookup is case insensitive and rejects the unknown`() {
+ assertEquals("mp3", FfmpegCommand.audioTargetFor("MP3")?.extension)
+ assertNull(FfmpegCommand.audioTargetFor("xyz"))
+ }
+
+ @Test
+ fun `the probe does not depend on ffmpeg being present`() {
+ assertEquals("command -v ffmpeg", FfmpegCommand.PROBE_COMMAND)
+ }
+}