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(media): compress, speed and concat, plus the CHANGELOG entry
Durganshu57bd865c7032
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ceef117..7b69442 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,20 @@ All notable changes to Gotcha are documented here.## [Unreleased]### Added+- **Audio & video editing.** A new `media_edit` tool edits media entirely+ on-device: trim a window out of a clip, pull a video's audio into its own+ file, mute a video, shrink one to a smaller resolution, speed it up or slow it+ down, and join several files end to end, plus an `info` read for duration,+ resolution and tracks. Video and audio files work the same way, so trimming a+ voice memo and trimming a 4K video are the same request. Trimming, extracting+ and muting copy the streams rather than re-encoding, so they finish in seconds+ and lose no quality at all; compressing, re-timing and joining do re-encode,+ and Gotcha now says which of the two happened so you know whether a file was+ degraded. Every operation writes a new file and leaves the original alone.+ Adding music, overlaying text and editing what is inside a frame are not+ possible, and DRM-protected media cannot be opened at all — a bundled+ `media_editing` skill teaches the assistant to say so rather than attempt a+ workaround.- **PDF editing.** A new `pdf_edit` tool reshapes PDFs entirely on-device: mergeseveral files into one, split into single pages, extract or delete a pagerange, and rotate pages, plus an `info` read for the page count. Encrypteddiff --git a/app/src/main/assets/skills/media_editing.json b/app/src/main/assets/skills/media_editing.jsonindex 0f0019d..fbbab2c 100644--- a/app/src/main/assets/skills/media_editing.json+++ b/app/src/main/assets/skills/media_editing.json@@ -2,7 +2,7 @@"id": "media_editing","targetPackageNames": [],"title": "Audio & Video Editing Skills",- "description": "Trim clips and split audio from video on-device with media_edit instead of a web converter or an editor app.",+ "description": "Trim, shrink, re-time and join audio and video on-device with media_edit instead of a web converter or an editor app.","requiresTools": ["media_edit"],@@ -21,7 +21,14 @@"soundtrack","voice","memo",- "podcast"+ "podcast",+ "compress",+ "shrink",+ "speed",+ "faster",+ "slower",+ "join",+ "merge"],- "instructions": "Never upload a video or audio file to a web converter, and never automate a video editor's UI to trim a clip. media_edit does it locally: the file never leaves the device, and there is no watermark, length limit or account.\n\nCall operation='info' FIRST whenever you need a timecode. It reports duration, tracks, resolution, rotation and codecs without decoding anything, so it is cheap. Never guess a duration from the file name or size, and never trim against a duration the user quoted from memory — check it.\n\nWhat it does:\n1. 'info' — what the file contains. Also the way to answer \"how long is this?\" or \"does this video have sound?\".\n2. 'trim' — keeps the window between 'start' and 'end' and drops the rest. Give at least one of them; 'start' alone runs to the end of the file, 'end' alone starts from the beginning.\n3. 'extract_audio' — writes the audio track as its own .m4a. This is \"rip the audio\", \"just the sound\", \"turn this video into a podcast episode\".\n4. 'remove_audio' — writes the video with the audio dropped. This is \"mute it\", \"remove the background noise\" (which it does by removing ALL sound — say so, because that is usually not what they hoped for).\n\nTimecodes take several forms: '1:23' (m:ss), '1:02:03' (h:mm:ss), '90s', '1m30s', '500ms', or plain seconds like '12.5'. A colon field holding 60 or more seconds is refused as ambiguous — write '1:30' or '90s', not '1:90'. Use 'end' as the end timecode to mean the end of the file.\n\nAll four operations work identically on video and on audio-only files. Trimming an .m4a voice memo and trimming a 4K video are the same call. The two exceptions are refused with an explanation: extracting audio from a file that has no audio track, and removing the audio from a file that is audio-only.\n\nThese operations copy the streams instead of re-encoding them, so they are fast even on a long video and lose no quality at all. The result message tells you which happened; if it ever says the file was re-encoded, pass that on, because repeated re-encoding visibly degrades a file.\n\nOutput rules that matter. Every operation writes a NEW file and leaves the input untouched. The output path CANNOT be the same as the input — unlike pdf_edit there is no in-place mode, because the encoder writes the target while still reading the source, which would destroy both. Pick a clearly derived name (VID_0001-trimmed.mp4, interview-audio.m4a) and tell the user where you put it. An existing output fails unless you pass overwrite=true; do not reflexively retry with overwrite after that error, since the file in the way may be one the user still wants. The output must end in .mp4 (video) or .m4a (audio only) — the muxer always writes an MP4 container, so any other extension would be a mislabelled file.\n\nThe hard limits, which you must state plainly rather than work around:\n• It CANNOT compress, resize, change resolution or bitrate, change playback speed, join or concatenate files, add background music, overlay text or a watermark, fade audio, or adjust volume. These are not yet implemented. Do not fake any of them by chaining other tools.\n• It CANNOT open DRM-protected media — anything bought or downloaded from a store. That is a property of the file, not a missing feature, and no retry will work.\n• It CANNOT edit what is inside a frame: no removing an object, no blurring a face, no cutting a middle section out and rejoining the ends (that needs concatenation).\nWhen asked for one of these, say so directly and offer what does work.\n\nIf a file will not open at all, it may be in a container Android's codecs cannot read (MKV, OGG, FLV are the usual ones). ffmpeg through run_termux_command is the fallback, but it requires Termux installed with the ffmpeg package, so offer it as an option rather than assuming it is there.\n\nFinding the file: phone video lives in /sdcard/DCIM/Camera, screen recordings in /sdcard/Movies, voice memos and music in /sdcard/Music or /sdcard/Recordings, downloads in /sdcard/Download, and WhatsApp media under /sdcard/Android/media/com.whatsapp. Use glob (e.g. '/sdcard/DCIM/Camera/*.mp4') rather than asking the user for a full path they will not know. When several match, use info on the likely ones and confirm which they meant before writing anything — trimming the wrong video looks like data loss."+ "instructions": "Never upload a video or audio file to a web converter, and never automate a video editor's UI to trim a clip. media_edit does it locally: the file never leaves the device, and there is no watermark, length limit or account.\n\nCall operation='info' FIRST whenever you need a timecode. It reports duration, tracks, resolution, rotation and codecs without decoding anything, so it is cheap. Never guess a duration from the file name or size, and never trim against a duration the user quoted from memory — check it.\n\nWhat it does:\n1. 'info' — what the file contains. Also the way to answer \"how long is this?\" or \"does this video have sound?\".\n2. 'trim' — keeps the window between 'start' and 'end' and drops the rest. Give at least one of them; 'start' alone runs to the end of the file, 'end' alone starts from the beginning.\n3. 'extract_audio' — writes the audio track as its own .m4a. This is \"rip the audio\", \"just the sound\", \"turn this video into a podcast episode\".\n4. 'remove_audio' — writes the video with the audio dropped. This is \"mute it\", \"remove the background noise\" (which it does by removing ALL sound — say so, because that is usually not what they hoped for).\n5. 'compress' — re-encodes smaller at 'height' (default 720). This is \"make it small enough to email/WhatsApp\". Compressing a file that is already that small or smaller is refused rather than silently degrading it.\n6. 'speed' — re-times by 'speed', between 0.25 and 4.0. Audio and video are re-timed together, so they stay in sync. 2.0 halves the duration.\n7. 'concat' — joins 'inputs' end to end, in exactly the order given. Confirm the order with the user when it is not obvious; a join in the wrong order looks like data loss to them. All inputs must be video, or all audio-only — mixing them is refused.\n\nTimecodes take several forms: '1:23' (m:ss), '1:02:03' (h:mm:ss), '90s', '1m30s', '500ms', or plain seconds like '12.5'. A colon field holding 60 or more seconds is refused as ambiguous — write '1:30' or '90s', not '1:90'. Use 'end' as the end timecode to mean the end of the file.\n\nAll four operations work identically on video and on audio-only files. Trimming an .m4a voice memo and trimming a 4K video are the same call. The two exceptions are refused with an explanation: extracting audio from a file that has no audio track, and removing the audio from a file that is audio-only.\n\nCost differs sharply between the two groups, and it is worth telling the user which they are getting. trim, extract_audio and remove_audio COPY the streams: they finish in seconds even on a long video and lose no quality whatsoever. compress, speed and concat RE-ENCODE: they run the whole file through the codec, which takes minutes and loses a little quality each time. The result message says which happened — pass that on, because repeated re-encoding visibly degrades a file and the user cannot see it coming.\n\nBecause re-encoding is slow, inputs longer than 30 minutes are refused for compress, speed and concat, and any export that overruns ten minutes is abandoned. When you hit either, do not retry the same call — trim the file to the part that is actually wanted first, and explain why you are doing that.\n\nOutput rules that matter. Every operation writes a NEW file and leaves the input untouched. The output path CANNOT be the same as the input — unlike pdf_edit there is no in-place mode, because the encoder writes the target while still reading the source, which would destroy both. Pick a clearly derived name (VID_0001-trimmed.mp4, interview-audio.m4a) and tell the user where you put it. An existing output fails unless you pass overwrite=true; do not reflexively retry with overwrite after that error, since the file in the way may be one the user still wants. The output must end in .mp4 (video) or .m4a (audio only) — the muxer always writes an MP4 container, so any other extension would be a mislabelled file.\n\nThe hard limits, which you must state plainly rather than work around:\n• It CANNOT add background music or any second audio track, overlay text, a watermark or an image, fade audio in or out, adjust volume, or change the bitrate directly. These are not implemented. Do not fake any of them by chaining other tools.\n• It CANNOT open DRM-protected media — anything bought or downloaded from a store. That is a property of the file, not a missing feature, and no retry will work.\n• It CANNOT edit what is inside a frame: no removing an object, no blurring a face, no colour grading, no stabilisation.\n• Cutting a middle section OUT of one file is possible, but only as two steps: trim the part before and the part after into separate files, then concat them. Say that is what you are doing, and clean up the intermediate files afterwards with delete_file.\nWhen asked for one of these, say so directly and offer what does work.\n\nIf a file will not open at all, it may be in a container Android's codecs cannot read (MKV, OGG, FLV are the usual ones). ffmpeg through run_termux_command is the fallback, but it requires Termux installed with the ffmpeg package, so offer it as an option rather than assuming it is there.\n\nFinding the file: phone video lives in /sdcard/DCIM/Camera, screen recordings in /sdcard/Movies, voice memos and music in /sdcard/Music or /sdcard/Recordings, downloads in /sdcard/Download, and WhatsApp media under /sdcard/Android/media/com.whatsapp. Use glob (e.g. '/sdcard/DCIM/Camera/*.mp4') rather than asking the user for a full path they will not know. When several match, use info on the likely ones and confirm which they meant before writing anything — trimming the wrong video looks like data loss."}diff --git a/app/src/main/java/com/gotcha/tools/MediaEditTool.kt b/app/src/main/java/com/gotcha/tools/MediaEditTool.ktindex e74f970..c1c4ae0 100644--- a/app/src/main/java/com/gotcha/tools/MediaEditTool.kt+++ b/app/src/main/java/com/gotcha/tools/MediaEditTool.kt@@ -1,6 +1,11 @@package com.gotcha.toolsimport android.content.Context+import androidx.annotation.OptIn+import androidx.media3.common.audio.SonicAudioProcessor+import androidx.media3.common.util.UnstableApi+import androidx.media3.effect.Presentation+import androidx.media3.effect.SpeedChangeEffectimport java.io.File/**@@ -22,6 +27,7 @@ import java.io.File* Only available to Operator (writes files).*/@Suppress("TooManyFunctions")+@OptIn(UnstableApi::class)class MediaEditTool(private val context: Context) {private val resolver = FileResolver(context)@@ -34,7 +40,25 @@ class MediaEditTool(private val context: Context) {*/const val MAX_MEDIA_BYTES = 2L * 1024 * 1024 * 1024- val OPERATIONS = listOf("info", "trim", "extract_audio", "remove_audio")+ val OPERATIONS = listOf("info", "trim", "extract_audio", "remove_audio", "compress", "speed", "concat")++ /** Keeps a concat from being handed an unbounded glob result. */+ const val MAX_CONCAT_INPUTS = 20++ /**+ * Above this, a re-encode will not finish inside [MediaExport.TIMEOUT_MS]+ * on a mid-range phone. Refusing up front with a usable suggestion beats+ * burning ten minutes to report a timeout. Stream-copy operations are+ * unaffected — they are bounded by disk speed, not by the codec.+ */+ const val MAX_REENCODE_DURATION_MS = 30L * 60 * 1000++ /** Playback-speed bounds. Outside these the audio resampler produces noise, not sound. */+ const val MIN_SPEED = 0.25+ const val MAX_SPEED = 4.0++ /** Default target height for compress — 720p is the usual "make it small enough to send". */+ const val DEFAULT_COMPRESS_HEIGHT = 720/*** Transformer's muxer writes an MP4 container whatever the output path is@@ -57,9 +81,12 @@ class MediaEditTool(private val context: Context) {suspend fun edit(operation: String,input: String? = null,+ inputs: List<String>? = null,output: String? = null,start: String? = null,end: String? = null,+ height: Int? = null,+ speed: Double? = null,overwrite: Boolean = false): ToolResult {val op = operation.trim().lowercase()@@ -68,16 +95,26 @@ class MediaEditTool(private val context: Context) {"Unknown operation '$operation'. Valid operations: ${OPERATIONS.joinToString(", ")}.")}- val source = input ?: return missing("input", op)return try {+ if (op == "concat") {+ return concat(inputs, output ?: return missing("output", op), overwrite)+ }+ val source = input ?: return missing("input", op)when (op) {"info" -> info(source)"trim" -> trim(source, output ?: return missing("output", op), start, end, overwrite)"extract_audio" -> extractAudio(source, output ?: return missing("output", op), overwrite)- else -> removeAudio(source, output ?: return missing("output", op), overwrite)+ "remove_audio" -> removeAudio(source, output ?: return missing("output", op), overwrite)+ "compress" -> compress(source, output ?: return missing("output", op), height, overwrite)+ else -> changeSpeed(+ source,+ output ?: return missing("output", op),+ speed ?: return missing("speed", op),+ overwrite+ )}} catch (e: Exception) {- ToolResult.error(describeFailure(e, source))+ ToolResult.error(describeFailure(e, input ?: inputs?.firstOrNull() ?: "the input"))}}@@ -166,6 +203,166 @@ class MediaEditTool(private val context: Context) {)}+ private suspend fun compress(+ input: String,+ output: String,+ height: Int?,+ overwrite: Boolean+ ): ToolResult {+ val targetHeight = height ?: DEFAULT_COMPRESS_HEIGHT+ if (targetHeight <= 0) {+ return ToolResult.error("height must be a positive number of pixels, e.g. 720. Got $targetHeight.")+ }+ val file = resolveInput(input).unwrap { return it }+ val target = resolveOutput(output, file, overwrite).unwrap { return it }+ val probe = MediaProbe.of(file)+ if (!probe.hasVideo) {+ return ToolResult.error(+ "'${file.name}' has no video track, and compressing audio is not supported. " ++ "Use trim to shorten it instead, or say that shrinking an audio file is not something this can do."+ )+ }+ tooLongToReencode(probe, file.name, "compress")?.let { return it }++ if (probe.displayHeight in 1..targetHeight) {+ return ToolResult.error(+ "'${file.name}' is already ${probe.displayWidth}x${probe.displayHeight}, which is no taller than the " ++ "requested ${targetHeight}p — re-encoding it would lose quality without saving meaningful space. " ++ "Tell the user it is already small enough."+ )+ }++ val export = MediaExport(context).run(+ input = file,+ output = target,+ videoEffects = listOf(Presentation.createForHeight(targetHeight))+ )+ export.failure()?.let { return it }+ return ToolResult.ok(+ "Compressed '${file.name}' from ${probe.displayWidth}x${probe.displayHeight} to ${targetHeight}p " ++ "into '${target.canonicalPath}' — ${resolver.formatSize(file.length())} became " ++ "${resolver.formatSize(target.length())}.${export.qualityNote()}"+ )+ }++ private suspend fun changeSpeed(+ input: String,+ output: String,+ speed: Double,+ overwrite: Boolean+ ): ToolResult {+ if (speed !in MIN_SPEED..MAX_SPEED || speed == 1.0) {+ return ToolResult.error(+ if (speed == 1.0) {+ "speed=1.0 would re-encode the file without changing anything. Pick a different speed, " ++ "or copy the file with write_file if a copy is what was wanted."+ } else {+ "speed must be between $MIN_SPEED and $MAX_SPEED — outside that the audio becomes unintelligible. " ++ "Got $speed."+ }+ )+ }+ val file = resolveInput(input).unwrap { return it }+ val target = resolveOutput(output, file, overwrite).unwrap { return it }+ val probe = MediaProbe.of(file)+ tooLongToReencode(probe, file.name, "speed")?.let { return it }++ // Both tracks have to be sped up by the same factor or they drift apart.+ val audio = if (probe.hasAudio) {+ listOf(SonicAudioProcessor().apply { setSpeed(speed.toFloat()) })+ } else {+ emptyList()+ }+ val video = if (probe.hasVideo) listOf(SpeedChangeEffect(speed.toFloat())) else emptyList()++ val export = MediaExport(context).run(+ input = file,+ output = target,+ videoEffects = video,+ audioProcessors = audio+ )+ export.failure()?.let { return it }+ val newDuration = if (probe.durationMs > 0) (probe.durationMs / speed).toLong() else 0L+ return ToolResult.ok(+ "Changed the speed of '${file.name}' to ${speed}x into '${target.canonicalPath}'" ++ if (newDuration > 0) {+ " — ${MediaTimeSpec.format(probe.durationMs)} became ${MediaTimeSpec.format(newDuration)}."+ } else {+ "."+ } + export.qualityNote()+ )+ }++ private suspend fun concat(inputs: List<String>?, output: String, overwrite: Boolean): ToolResult {+ if (inputs.isNullOrEmpty()) {+ return ToolResult.error(+ "concat needs an 'inputs' array of at least two media paths, in the order they should be joined."+ )+ }+ if (inputs.size < 2) {+ return ToolResult.error(+ "concat needs at least two input files — got ${inputs.size}. To copy one file, use trim."+ )+ }+ if (inputs.size > MAX_CONCAT_INPUTS) {+ return ToolResult.error(+ "Too many inputs (${inputs.size}). Join at most $MAX_CONCAT_INPUTS files at a time."+ )+ }+ val files = inputs.map { path -> resolveInput(path).unwrap { return it } }+ val target = resolveOutput(output, files.first(), overwrite).unwrap { return it }+ files.drop(1).forEach { file ->+ if (file.canonicalPath == target.canonicalPath) {+ return ToolResult.error(+ "Output '${target.canonicalPath}' is also one of the inputs, which would destroy it mid-read. " ++ "Write to a new path."+ )+ }+ }++ val probes = files.map { MediaProbe.of(it) }+ // Mixing an audio-only file into a video sequence produces a result with a+ // silent gap or no video at all, depending on order — never what was meant.+ val withVideo = probes.count { it.hasVideo }+ if (withVideo != 0 && withVideo != probes.size) {+ val audioOnly = files.filterIndexed { i, _ -> !probes[i].hasVideo }.joinToString(", ") { it.name }+ return ToolResult.error(+ "Cannot join video and audio-only files together — $audioOnly ${if (withVideo == probes.size - 1) "has" else "have"} " ++ "no video track. Extract the audio from the videos first if an audio-only result is what was wanted."+ )+ }+ val totalMs = probes.sumOf { it.durationMs }+ if (totalMs > MAX_REENCODE_DURATION_MS) {+ return ToolResult.error(+ "The joined result would be ${MediaTimeSpec.format(totalMs)}, past the " ++ "${MediaTimeSpec.format(MAX_REENCODE_DURATION_MS)} ceiling for an operation that re-encodes. " ++ "Join fewer files, or trim them first."+ )+ }++ val export = MediaExport(context).concat(files, target)+ export.failure()?.let { return it }+ return ToolResult.ok(+ "Joined ${files.size} files into '${target.canonicalPath}' — ${MediaTimeSpec.format(totalMs)}, " ++ "${resolver.formatSize(target.length())}. Source order: " ++ files.joinToString(", ") { it.name } + "." + export.qualityNote()+ )+ }++ /**+ * Re-encoding operations are bounded by the codec, not by disk, so a long+ * input will exhaust [MediaExport.TIMEOUT_MS] and report nothing useful after+ * ten minutes of work. Refuse early with something the model can act on.+ */+ private fun tooLongToReencode(probe: MediaProbe, name: String, operation: String): ToolResult? {+ if (probe.durationMs <= MAX_REENCODE_DURATION_MS) return null+ return ToolResult.error(+ "'$name' is ${MediaTimeSpec.format(probe.durationMs)}, past the " ++ "${MediaTimeSpec.format(MAX_REENCODE_DURATION_MS)} ceiling for '$operation', which re-encodes the " ++ "whole file. Trim it to the part that is actually wanted first, and say why."+ )+ }+// ---- shared plumbing ----private fun resolveInput(path: String): Result<File> {diff --git a/app/src/main/java/com/gotcha/tools/MediaExport.kt b/app/src/main/java/com/gotcha/tools/MediaExport.ktindex 4fdb8d2..722e7e6 100644--- a/app/src/main/java/com/gotcha/tools/MediaExport.kt+++ b/app/src/main/java/com/gotcha/tools/MediaExport.kt@@ -3,13 +3,20 @@ package com.gotcha.toolsimport android.content.Contextimport android.net.Uriimport androidx.annotation.OptIn+import androidx.media3.common.Effectimport androidx.media3.common.MediaItem+import androidx.media3.common.audio.AudioProcessorimport androidx.media3.common.util.UnstableApiimport androidx.media3.transformer.Composition+import androidx.media3.transformer.DefaultEncoderFactoryimport androidx.media3.transformer.EditedMediaItem+import androidx.media3.transformer.EditedMediaItemSequence+import androidx.media3.transformer.Effectsimport androidx.media3.transformer.ExportExceptionimport androidx.media3.transformer.ExportResultimport androidx.media3.transformer.Transformer+import androidx.media3.transformer.VideoEncoderSettings+import com.google.common.collect.ImmutableListimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.suspendCancellableCoroutineimport kotlinx.coroutines.withContext@@ -78,33 +85,50 @@ class MediaExport(private val context: Context) {* track dropped. With no clip and no removals this is a plain container* rewrite, which Transformer still performs as a stream copy.*/+ @Suppress("LongParameterList")suspend fun run(input: File,output: File,clip: LongRange? = null,removeAudio: Boolean = false,- removeVideo: Boolean = false+ removeVideo: Boolean = false,+ videoEffects: List<Effect> = emptyList(),+ audioProcessors: List<AudioProcessor> = emptyList(),+ videoBitrateBps: Int? = null): Outcome {val outcome = withTimeoutOrNull(TIMEOUT_MS) {withContext(Dispatchers.Main) {- export(input, output, clip, removeAudio, removeVideo)+ export(+ input = input,+ output = output,+ clip = clip,+ removeAudio = removeAudio,+ removeVideo = removeVideo,+ videoEffects = videoEffects,+ audioProcessors = audioProcessors,+ videoBitrateBps = videoBitrateBps+ )}}- if (outcome == null) {- // A half-written file is worse than none: it looks like a successful- // edit to anything that only checks for existence.- runCatching { if (output.exists()) output.delete() }- return Outcome(- error = ToolResult.error(- "The export did not finish within ${TIMEOUT_MS / 60_000} minutes and was abandoned. " +- "This usually means the file is very long or very high-resolution. Trim it to a shorter " +- "window first, and tell the user why."- ),- videoEncoder = null,- audioEncoder = null- )- }- return outcome+ return outcome ?: timedOut(output)+ }++ /**+ * A half-written output is worse than none: it looks like a successful edit+ * to anything that only checks for existence, so it is deleted before the+ * failure is reported.+ */+ private fun timedOut(output: File): Outcome {+ runCatching { if (output.exists()) output.delete() }+ return Outcome(+ error = ToolResult.error(+ "The export did not finish within ${TIMEOUT_MS / 60_000} minutes and was abandoned. " ++ "This usually means the file is very long or very high-resolution. Trim it to a shorter " ++ "window first, and tell the user why."+ ),+ videoEncoder = null,+ audioEncoder = null+ )}@Suppress("LongParameterList")@@ -113,10 +137,61 @@ class MediaExport(private val context: Context) {output: File,clip: LongRange?,removeAudio: Boolean,- removeVideo: Boolean+ removeVideo: Boolean,+ videoEffects: List<Effect>,+ audioProcessors: List<AudioProcessor>,+ videoBitrateBps: Int?): Outcome = suspendCancellableCoroutine { continuation ->- val item = MediaItem.Builder()- .setUri(Uri.fromFile(input))+ val edited = EditedMediaItem.Builder(mediaItem(input, clip))+ .setRemoveAudio(removeAudio)+ .setRemoveVideo(removeVideo)+ .setEffects(Effects(ImmutableList.copyOf(audioProcessors), ImmutableList.copyOf(videoEffects)))+ .build()++ val transformer = transformerBuilder(output, videoBitrateBps, continuation)+ .build()++ continuation.invokeOnCancellation {+ // cancel() must run on the thread that built the Transformer.+ runCatching { transformer.cancel() }+ }+ transformer.start(edited, output.absolutePath)+ }++ /**+ * Joins [inputs] end to end into [output].+ *+ * A concatenation is the one operation that cannot be expressed as an edit of+ * a single item, so it builds a [Composition] instead. Transformer re-encodes+ * whatever it must to make mismatched sources line up, which is why+ * [MediaEditTool] warns about the cost before calling this.+ */+ suspend fun concat(inputs: List<File>, output: File): Outcome {+ val outcome = withTimeoutOrNull(TIMEOUT_MS) {+ withContext(Dispatchers.Main) { concatOnLooper(inputs, output) }+ }+ return outcome ?: timedOut(output)+ }++ private suspend fun concatOnLooper(+ inputs: List<File>,+ output: File+ ): Outcome = suspendCancellableCoroutine { continuation ->+ val sequence = EditedMediaItemSequence(+ inputs.map { EditedMediaItem.Builder(mediaItem(it, clip = null)).build() }+ )+ val composition = Composition.Builder(ImmutableList.of(sequence)).build()++ val transformer = transformerBuilder(output, videoBitrateBps = null, continuation = continuation)+ .build()++ continuation.invokeOnCancellation { runCatching { transformer.cancel() } }+ transformer.start(composition, output.absolutePath)+ }++ private fun mediaItem(file: File, clip: LongRange?): MediaItem =+ MediaItem.Builder()+ .setUri(Uri.fromFile(file)).apply {clip?.let {setClippingConfiguration(@@ -129,12 +204,12 @@ class MediaExport(private val context: Context) {}.build()- val edited = EditedMediaItem.Builder(item)- .setRemoveAudio(removeAudio)- .setRemoveVideo(removeVideo)- .build()-- val transformer = Transformer.Builder(context)+ private fun transformerBuilder(+ output: File,+ videoBitrateBps: Int?,+ continuation: kotlinx.coroutines.CancellableContinuation<Outcome>+ ): Transformer.Builder {+ val builder = Transformer.Builder(context).addListener(object : Transformer.Listener {override fun onCompleted(composition: Composition, result: ExportResult) {if (continuation.isActive) {@@ -157,7 +232,7 @@ class MediaExport(private val context: Context) {if (continuation.isActive) {continuation.resume(Outcome(- error = ToolResult.error(describeExportError(exception, input)),+ error = ToolResult.error(describeExportError(exception, output)),videoEncoder = null,audioEncoder = null)@@ -165,13 +240,14 @@ class MediaExport(private val context: Context) {}}})- .build()-- continuation.invokeOnCancellation {- // cancel() must run on the thread that built the Transformer.- runCatching { transformer.cancel() }+ videoBitrateBps?.let { bitrate ->+ builder.setEncoderFactory(+ DefaultEncoderFactory.Builder(context)+ .setRequestedVideoEncoderSettings(VideoEncoderSettings.Builder().setBitrate(bitrate).build())+ .build()+ )}- transformer.start(edited, output.absolutePath)+ return builder}/**diff --git a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt b/app/src/main/java/com/gotcha/tools/ToolDefinitions.ktindex 2a28136..ed417d3 100644--- a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt+++ b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt@@ -1291,14 +1291,16 @@ object ToolDefinitions {val mediaEdit = tool("media_edit","Edit an audio or video file on-device: trim a window out of it, pull its audio track into a " +- "separate file, or strip the audio from a video. Also reports duration, resolution, tracks and " +- "codecs with operation='info' — call that FIRST whenever you need a timecode, so you are trimming " +- "against the real duration rather than a guess. Works the same on video and on audio-only files. " +- "Every operation writes a NEW file and never modifies the input; the output cannot be the input, " +- "because the encoder writes it while still reading from it. These operations copy the streams " +- "rather than re-encoding, so they are fast and lossless. It CANNOT re-encode, compress, resize, " +- "change speed, join files, or add music yet, and it cannot open DRM-protected media at all — say " +- "so plainly instead of attempting a workaround.",+ "separate file, strip the audio from a video, shrink it, change its playback speed, or join " ++ "several files end to end. Also reports duration, resolution, tracks and codecs with " ++ "operation='info' — call that FIRST whenever you need a timecode or a resolution, so you are " ++ "working against real numbers rather than a guess. Works the same on video and on audio-only " ++ "files. Every operation writes a NEW file and never modifies the input; the output cannot be the " ++ "input, because the encoder writes it while still reading from it. trim, extract_audio and " ++ "remove_audio copy the streams rather than re-encoding, so they are fast and lossless; compress, " ++ "speed and concat re-encode, so they take much longer and lose a little quality. It cannot add " ++ "music, overlay text or a watermark, blur or remove anything inside a frame, or open " ++ "DRM-protected media at all — say so plainly instead of attempting a workaround.",schema {putJsonObject("properties") {putJsonObject("operation") {@@ -1308,7 +1310,8 @@ object ToolDefinitions {"description","info = duration, tracks, resolution and codecs; trim = keep the window between " +"'start' and 'end'; extract_audio = write the audio track as its own file; " +- "remove_audio = write the video with its audio dropped."+ "remove_audio = write the video with its audio dropped; compress = re-encode " ++ "smaller at 'height'; speed = re-time by 'speed'; concat = join 'inputs' in order.")}putJsonObject("input") {@@ -1316,7 +1319,7 @@ object ToolDefinitions {put("description","Path of the source audio or video file, e.g. '/sdcard/DCIM/Camera/VID_0001.mp4'. " +- "Required by every operation."+ "Required by every operation except concat, which takes 'inputs' instead.")}putJsonObject("output") {@@ -1346,6 +1349,33 @@ object ToolDefinitions {"and 'end'.")}+ putJsonObject("inputs") {+ put("type", "array")+ putJsonObject("items") { put("type", "string") }+ put(+ "description",+ "concat only: two or more media paths, in the order they should be joined. They must " ++ "all be video or all be audio-only."+ )+ }+ putJsonObject("height") {+ put("type", "integer")+ put(+ "description",+ "compress only: target height in pixels, e.g. 720 or 480. Defaults to 720. Width " ++ "follows the original aspect ratio. Compressing something already this small is " ++ "refused."+ )+ }+ putJsonObject("speed") {+ put("type", "number")+ put(+ "description",+ "speed only: playback multiplier between 0.25 and 4.0. 2.0 plays twice as fast and " ++ "halves the duration; 0.5 plays at half speed. Audio and video are re-timed " ++ "together."+ )+ }putJsonObject("overwrite") {put("type", "boolean")put(@@ -1355,10 +1385,7 @@ object ToolDefinitions {)}}- putJsonArray("required") {- add("operation")- add("input")- }+ putJsonArray("required") { add("operation") }})diff --git a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt b/app/src/main/java/com/gotcha/tools/ToolExecutor.ktindex 61fb3ac..6bb1659 100644--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt@@ -13,6 +13,7 @@ import kotlinx.serialization.json.JsonElementimport kotlinx.serialization.json.JsonObjectimport kotlinx.serialization.json.JsonPrimitiveimport kotlinx.serialization.json.booleanOrNull+import kotlinx.serialization.json.doubleOrNullimport kotlinx.serialization.json.intOrNullimport kotlinx.serialization.json.jsonArrayimport kotlinx.serialization.json.jsonPrimitive@@ -236,9 +237,12 @@ class ToolExecutor("media_edit" -> mediaEditTool.edit(operation = args.requireString("operation") ?: return missing("operation"),input = args.requireString("input"),+ inputs = args.requireStringList("inputs"),output = args.requireString("output"),start = args.requireString("start"),end = args.requireString("end"),+ height = args.requireInt("height"),+ speed = args["speed"]?.jsonPrimitive?.doubleOrNull,overwrite = args.requireBoolean("overwrite") ?: false)"open_app" -> systemTool.openApp(args.requireString("package_name") ?: return missing("package_name"))diff --git a/app/src/test/java/com/gotcha/tools/MediaEditToolTest.kt b/app/src/test/java/com/gotcha/tools/MediaEditToolTest.ktindex b43ba6b..68609c3 100644--- a/app/src/test/java/com/gotcha/tools/MediaEditToolTest.kt+++ b/app/src/test/java/com/gotcha/tools/MediaEditToolTest.kt@@ -50,15 +50,29 @@ class MediaEditToolTest {private fun placeholder(name: String): File =File(dir, name).apply { writeBytes(ByteArray(1024)) }+ @Suppress("LongParameterList")private fun edit(operation: String,input: String? = null,+ inputs: List<String>? = null,output: String? = null,start: String? = null,end: String? = null,+ height: Int? = null,+ speed: Double? = null,overwrite: Boolean = false): ToolResult = runBlocking {- tool.edit(operation, input, output, start, end, overwrite)+ tool.edit(+ operation = operation,+ input = input,+ inputs = inputs,+ output = output,+ start = start,+ end = end,+ height = height,+ speed = speed,+ overwrite = overwrite+ )}// ---- operation and argument validation ----@@ -156,6 +170,99 @@ class MediaEditToolTest {}}+ // ---- re-encoding operations ----++ @Test+ fun `speed outside the intelligible range is refused`() {+ listOf(0.1, 10.0, 0.0).forEach { rate ->+ val result = edit(+ "speed",+ input = placeholder("a.mp4").path,+ output = File(dir, "out.mp4").path,+ speed = rate+ )+ assertFalse(rate.toString(), result.success)+ assertTrue(rate.toString(), result.message.contains("between"))+ }+ }++ @Test+ fun `speed of exactly one is refused as a pointless re-encode`() {+ val result = edit(+ "speed",+ input = placeholder("a.mp4").path,+ output = File(dir, "out.mp4").path,+ speed = 1.0+ )+ assertFalse(result.success)+ assertTrue(result.message.contains("without changing anything"))+ }++ @Test+ fun `speed without a rate names the missing parameter`() {+ val result = edit("speed", input = placeholder("a.mp4").path, output = File(dir, "out.mp4").path)+ assertFalse(result.success)+ assertTrue(result.message.contains("speed"))+ }++ @Test+ fun `a non-positive compress height is refused`() {+ val result = edit(+ "compress",+ input = placeholder("a.mp4").path,+ output = File(dir, "out.mp4").path,+ height = 0+ )+ assertFalse(result.success)+ assertTrue(result.message.contains("positive"))+ }++ @Test+ fun `concat needs at least two inputs`() {+ val single = edit("concat", inputs = listOf(placeholder("a.mp4").path), output = File(dir, "out.mp4").path)+ assertFalse(single.success)+ assertTrue(single.message.contains("at least two"))++ val none = edit("concat", output = File(dir, "out.mp4").path)+ assertFalse(none.success)+ assertTrue(none.message.contains("at least two"))+ }++ @Test+ fun `concat refuses more inputs than it will join at once`() {+ val many = (1..MediaEditTool.MAX_CONCAT_INPUTS + 1).map { placeholder("clip$it.mp4").path }+ val result = edit("concat", inputs = many, output = File(dir, "out.mp4").path)+ assertFalse(result.success)+ assertTrue(result.message.contains("${MediaEditTool.MAX_CONCAT_INPUTS}"))+ }++ @Test+ fun `concat refuses to write over any of its own inputs`() {+ // resolveOutput catches the first input; the later ones need their own check,+ // and overwriting input three is just as destructive as overwriting input one.+ val first = placeholder("a.mp4")+ val second = placeholder("b.mp4")+ val result = edit(+ "concat",+ inputs = listOf(first.path, second.path),+ output = second.path,+ overwrite = true+ )+ assertFalse(result.success)+ assertTrue(result.message.contains("also one of the inputs"))+ }++ @Test+ fun `concat reports a missing input rather than silently joining the rest`() {+ val result = edit(+ "concat",+ inputs = listOf(placeholder("a.mp4").path, File(dir, "gone.mp4").path),+ output = File(dir, "out.mp4").path+ )+ assertFalse(result.success)+ assertTrue(result.message.contains("does not exist"))+ }+@Testfun `the supported output containers pass the extension guard`() {// These get past validation and fail later at the codec, which Robolectricdiff --git a/app/src/test/resources/feature-test-coverage.json b/app/src/test/resources/feature-test-coverage.jsonindex 9154921..1a0d7c9 100644--- a/app/src/test/resources/feature-test-coverage.json+++ b/app/src/test/resources/feature-test-coverage.json@@ -423,7 +423,7 @@"com.gotcha.tools.MediaEditToolTest","com.gotcha.tools.MediaTimeSpecTest"],- "notes": "timecode parsing and trim-window arithmetic on the JVM (m:ss, h:mm:ss, unit and plain-seconds forms, ambiguous-field and backwards-window refusals, clamping an over-long end), plus every guard that runs before a codec is touched: unknown operation, missing arguments, trim with no bounds, refusal to write back over the input, existing-output refusal, directory output and the MP4/M4A container check. The export itself is device-only — Media3 Transformer drives MediaCodec, which is native and has no Robolectric shadow, so trim/extract_audio/remove_audio output must be verified by hand on hardware"+ "notes": "timecode parsing and trim-window arithmetic on the JVM (m:ss, h:mm:ss, unit and plain-seconds forms, ambiguous-field and backwards-window refusals, clamping an over-long end), plus every guard that runs before a codec is touched: unknown operation, missing arguments, trim with no bounds, refusal to write back over the input or over any concat input, existing-output refusal, directory output, the MP4/M4A container check, speed bounds and the pointless speed=1.0 re-encode, non-positive compress height, and concat's input-count limits. The export itself is device-only — Media3 Transformer drives MediaCodec, which is native and has no Robolectric shadow, so the output of trim, extract_audio, remove_audio, compress, speed and concat must be verified by hand on hardware"},{"tool": "glob",diff --git a/docs/FEATURE_TEST_COVERAGE.md b/docs/FEATURE_TEST_COVERAGE.mdindex d4585f3..04fa701 100644--- a/docs/FEATURE_TEST_COVERAGE.md+++ b/docs/FEATURE_TEST_COVERAGE.md@@ -65,7 +65,7 @@ Every tool the assistant can call is listed below, together with how it is verif| `lock_screen` | `MANUAL_ONLY` | Needs an active Device Admin registration, which cannot be granted non-interactively. || `mark_email_read` | `UNIT` | `EmailToolsTest` — read/unread toggle routed to the right backend || `media_control` | `UNIT` | `MediaSelectionTest` — action parsing and active-session selection |-| `media_edit` | `ROBOLECTRIC` | `MediaEditToolTest`, `MediaTimeSpecTest` — timecode parsing and trim-window arithmetic on the JVM (m:ss, h:mm:ss, unit and plain-seconds forms, ambiguous-field and backwards-window refusals, clamping an over-long end), plus every guard that runs before a codec is touched: unknown operation, missing arguments, trim with no bounds, refusal to write back over the input, existing-output refusal, directory output and the MP4/M4A container check. The export itself is device-only — Media3 Transformer drives MediaCodec, which is native and has no Robolectric shadow, so trim/extract_audio/remove_audio output must be verified by hand on hardware |+| `media_edit` | `ROBOLECTRIC` | `MediaEditToolTest`, `MediaTimeSpecTest` — timecode parsing and trim-window arithmetic on the JVM (m:ss, h:mm:ss, unit and plain-seconds forms, ambiguous-field and backwards-window refusals, clamping an over-long end), plus every guard that runs before a codec is touched: unknown operation, missing arguments, trim with no bounds, refusal to write back over the input or over any concat input, existing-output refusal, directory output, the MP4/M4A container check, speed bounds and the pointless speed=1.0 re-encode, non-positive compress height, and concat's input-count limits. The export itself is device-only — Media3 Transformer drives MediaCodec, which is native and has no Robolectric shadow, so the output of trim, extract_audio, remove_audio, compress, speed and concat must be verified by hand on hardware || `notion_append_to_page` | `UNIT` | `NotionToolsTest` — block append request shape || `notion_create_page` | `UNIT` | `NotionToolsTest` — parent/title handling and request shape || `pause_audio_recording` | `MANUAL_ONLY` | Needs real device hardware; the emulator has no faithful stand-in for this sensor/radio. |