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): media3 Transformer dependency, probe and export plumbing
Durganshufff003e2deb2
diff --git a/app/build.gradle.kts b/app/build.gradle.ktsindex fff4f54..eddbb51 100644--- a/app/build.gradle.kts+++ b/app/build.gradle.kts@@ -372,6 +372,25 @@ dependencies {// while isMinifyEnabled is false — enabling R8 would strip most of it.implementation("com.tom-roush:pdfbox-android:2.0.27.0")+ // Media3 Transformer: on-device audio/video editing (MediaEditTool). Wraps+ // MediaCodec/MediaMuxer, so edits are hardware-accelerated and — crucially —+ // transmuxed rather than re-encoded when the edit does not touch pixels, which+ // is what makes a trim take seconds instead of minutes. media3-effect carries+ // the pixel-touching transformations (scale, rotate, speed).+ //+ // Pinned to 1.4.1 deliberately: media3 1.5.0+ requires compileSdk 35 and this+ // module is on 34. Bump both together or not at all.+ //+ // ffmpeg-kit was the obvious alternative and was rejected: its maintainer+ // retired the project and pulled the prebuilt binaries, it adds tens of MB per+ // ABI, and being software-only it is slower on-device than the hardware path.+ // run_termux_command remains the escape hatch for formats MediaCodec cannot+ // open (see the media_editing skill).+ val media3Version = "1.4.1"+ implementation("androidx.media3:media3-transformer:$media3Version")+ implementation("androidx.media3:media3-effect:$media3Version")+ implementation("androidx.media3:media3-common:$media3Version")+// Connectors: Custom Tabs for the BYO-OAuth consent flowimplementation("androidx.browser:browser:1.8.0")diff --git a/app/src/main/java/com/gotcha/tools/MediaEditTool.kt b/app/src/main/java/com/gotcha/tools/MediaEditTool.ktnew file mode 100644index 0000000..7a7391e--- /dev/null+++ b/app/src/main/java/com/gotcha/tools/MediaEditTool.kt@@ -0,0 +1,271 @@+package com.gotcha.tools++import android.content.Context+import java.io.File++/**+ * On-device audio and video editing on top of Media3 Transformer.+ *+ * Covers the operations that do not require re-typesetting a frame: reporting+ * what a file contains, trimming a window out of it, and splitting the audio+ * and video tracks apart. Media3 transmuxes rather than re-encodes when an edit+ * does not touch pixels, so these are stream copies — a trim of a long video+ * finishes in seconds and loses no quality.+ *+ * Audio and video are the same code path throughout: a Transformer export of an+ * .m4a is a video export with no video track. The operations that genuinely+ * cannot apply to one or the other ([removeAudio] of an audio-only file) are+ * refused against [MediaProbe] rather than silently writing an empty file.+ *+ * Everything reads and writes through [FileResolver], so shared-storage paths+ * raise the usual "All files access" permission result rather than throwing.+ * Only available to Operator (writes files).+ */+@Suppress("TooManyFunctions")+class MediaEditTool(private val context: Context) {++ private val resolver = FileResolver(context)++ companion object {+ /**+ * Per-file input cap. Far higher than [PdfTool.MAX_PDF_BYTES] because the+ * transmux path streams through the container rather than holding it in+ * memory; this guards against a runaway path, not against heap pressure.+ */+ const val MAX_MEDIA_BYTES = 2L * 1024 * 1024 * 1024++ val OPERATIONS = listOf("info", "trim", "extract_audio", "remove_audio")++ /**+ * Transformer's muxer writes an MP4 container whatever the output path is+ * named, so anything else would be a mislabelled file that some players+ * refuse and the user cannot diagnose. .m4a is the audio-only spelling of+ * the same container, which is why it is allowed alongside .mp4.+ */+ val OUTPUT_EXTENSIONS = listOf("mp4", "m4a")+ }++ /**+ * Single entry point; [operation] selects the branch. Arguments that do not+ * apply to the chosen operation are ignored rather than rejected, so a model+ * that over-supplies (a `start` on an info call) still succeeds.+ *+ * Suspending because a Transformer export is asynchronous and can outlast any+ * reasonable blocking call — see [MediaExport].+ */+ @Suppress("LongParameterList", "ReturnCount")+ suspend fun edit(+ operation: String,+ input: String? = null,+ output: String? = null,+ start: String? = null,+ end: String? = null,+ overwrite: Boolean = false+ ): ToolResult {+ val op = operation.trim().lowercase()+ if (op !in OPERATIONS) {+ return ToolResult.error(+ "Unknown operation '$operation'. Valid operations: ${OPERATIONS.joinToString(", ")}."+ )+ }+ val source = input ?: return missing("input", op)+ return try {+ 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)+ }+ } catch (e: Exception) {+ ToolResult.error(describeFailure(e, source))+ }+ }++ // ---- operations ----++ private fun info(input: String): ToolResult {+ val file = resolveInput(input).unwrap { return it }+ val probe = MediaProbe.of(file)+ return ToolResult.ok(+ "'${file.canonicalPath}': ${probe.describe()}, ${resolver.formatSize(file.length())}."+ )+ }++ private suspend fun trim(+ input: String,+ output: String,+ start: String?,+ end: String?,+ overwrite: Boolean+ ): ToolResult {+ if (start == null && end == null) {+ return ToolResult.error(+ "trim needs at least one of 'start' and 'end' — with neither, the output would be a copy of the input."+ )+ }+ val file = resolveInput(input).unwrap { return it }+ val probe = MediaProbe.of(file)+ val target = resolveOutput(output, file, overwrite).unwrap { return it }+ val window = MediaTimeSpec.parseRange(start, end, probe.durationMs)+ .getOrElse { return ToolResult.error(it.message.orEmpty()) }++ val export = MediaExport(context).run(+ input = file,+ output = target,+ clip = window+ )+ export.failure()?.let { return it }++ val length = window.last - window.first+ return ToolResult.ok(+ "Trimmed ${MediaTimeSpec.format(window.first)}–${MediaTimeSpec.format(window.last)} " ++ "(${MediaTimeSpec.format(length)}) out of '${file.name}' into '${target.canonicalPath}' — " ++ "${resolver.formatSize(target.length())}.${export.qualityNote()}"+ )+ }++ private suspend fun extractAudio(input: String, output: String, overwrite: Boolean): ToolResult {+ val file = resolveInput(input).unwrap { return it }+ val probe = MediaProbe.of(file)+ if (!probe.hasAudio) {+ return ToolResult.error(+ "'${file.name}' has no audio track, so there is nothing to extract. Call operation='info' to see " ++ "what a file contains before choosing an operation."+ )+ }+ val target = resolveOutput(output, file, overwrite).unwrap { return it }+ val export = MediaExport(context).run(input = file, output = target, removeVideo = true)+ export.failure()?.let { return it }+ return ToolResult.ok(+ "Extracted the audio track of '${file.name}' into '${target.canonicalPath}' — " ++ "${MediaTimeSpec.format(probe.durationMs)}, ${resolver.formatSize(target.length())}." ++ export.qualityNote()+ )+ }++ private suspend fun removeAudio(input: String, output: String, overwrite: Boolean): ToolResult {+ val file = resolveInput(input).unwrap { return it }+ val probe = MediaProbe.of(file)+ if (probe.isAudioOnly) {+ return ToolResult.error(+ "'${file.name}' is an audio-only file, so removing its audio would leave an empty file. " ++ "Did you mean to trim it, or to delete it with delete_file?"+ )+ }+ if (!probe.hasAudio) {+ return ToolResult.error("'${file.name}' already has no audio track — there is nothing to remove.")+ }+ val target = resolveOutput(output, file, overwrite).unwrap { return it }+ val export = MediaExport(context).run(input = file, output = target, removeAudio = true)+ export.failure()?.let { return it }+ return ToolResult.ok(+ "Muted '${file.name}' into '${target.canonicalPath}' — video kept, audio track dropped, " ++ "${resolver.formatSize(target.length())}.${export.qualityNote()}"+ )+ }++ // ---- shared plumbing ----++ private fun resolveInput(path: String): Result<File> {+ val file = when (val resolved = resolver.resolveForRead(path)) {+ is FileResolver.ResolveResult.PermissionNeeded -> return Result.failure(ResultCarrier(resolved.result))+ is FileResolver.ResolveResult.Error -> return fail(resolved.message)+ is FileResolver.ResolveResult.Ok -> resolved.file+ }+ resolver.checkReadPermission(file)?.let { return Result.failure(ResultCarrier(it)) }+ if (!file.exists()) {+ return fail(+ "Media file '$path' does not exist (resolved: ${file.canonicalPath}). " ++ "You may use list_files or glob to find it."+ )+ }+ if (!file.isFile) return fail("'$path' is not a regular file.")+ if (file.length() > MAX_MEDIA_BYTES) {+ return fail(+ "'${file.name}' is ${resolver.formatSize(file.length())}; " ++ "the limit is ${resolver.formatSize(MAX_MEDIA_BYTES)}."+ )+ }+ return Result.success(file)+ }++ /**+ * Unlike [PdfTool], writing back over the input is refused outright rather+ * than routed through a temp file: Transformer reads the source while the+ * muxer writes the target, so an in-place edit truncates the file mid-read+ * and loses both copies.+ */+ private fun resolveOutput(path: String, input: File, overwrite: Boolean): Result<File> {+ val file = when (val resolved = resolver.resolveForWrite(path)) {+ is FileResolver.ResolveResult.PermissionNeeded -> return Result.failure(ResultCarrier(resolved.result))+ is FileResolver.ResolveResult.Error -> return fail(resolved.message)+ is FileResolver.ResolveResult.Ok -> resolved.file+ }+ resolver.checkWritePermission(file)?.let { return Result.failure(ResultCarrier(it)) }+ if (file.isDirectory) {+ return fail("Output '$path' is a directory. Give the full path of the file to write.")+ }+ if (file.canonicalPath == input.canonicalPath) {+ return fail(+ "Output cannot be the same file as the input — the encoder writes it while still reading from it, " ++ "which would destroy both. Write to a new path such as " ++ "'${input.nameWithoutExtension}-edited.${input.extension}' and tell the user where it went."+ )+ }+ val extension = file.extension.lowercase()+ if (extension !in OUTPUT_EXTENSIONS) {+ return fail(+ "Output '$path' ends in '.$extension', but this tool always writes an MP4 container — " ++ "name it .mp4 for video or .m4a for audio-only. Converting to ${extension.ifEmpty { "that format" }} " ++ "needs ffmpeg via run_termux_command."+ )+ }+ if (file.exists() && !overwrite) {+ return fail(+ "'${file.canonicalPath}' already exists. Pass overwrite=true to replace it, " ++ "or choose a different output path."+ )+ }+ file.parentFile?.let { parent ->+ if (!parent.exists() && !parent.mkdirs()) {+ return fail("Could not create the output directory '${parent.canonicalPath}'.")+ }+ }+ return Result.success(file)+ }++ /**+ * The platform's own messages here are unusable by a model — a DRM-protected+ * file reports "Failed to instantiate extractor", which reads like a bug in+ * the app rather than a file it is never going to be allowed to open.+ */+ private fun describeFailure(e: Exception, path: String): String {+ val name = e.javaClass.simpleName+ val message = e.message.orEmpty()+ return when {+ message.contains("DRM", ignoreCase = true) || message.contains("crypto", ignoreCase = true) ->+ "'$path' is DRM-protected, so it cannot be read or edited. This applies to anything bought or " ++ "streamed from a store — tell the user plainly rather than retrying."+ name == "IOException" || message.contains("extractor", ignoreCase = true) ->+ "Could not open '$path' as a media file. It may be corrupt, incomplete, or in a container Android " ++ "cannot read. Call operation='info' to check, and note that exotic formats (MKV, OGG) may need " ++ "ffmpeg via run_termux_command instead."+ else -> "Media operation failed: ${message.ifEmpty { name }}"+ }+ }++ private fun missing(param: String, operation: String) =+ ToolResult.error("Missing required parameter '$param' for operation '$operation'.")++ /** Carries an already-formed [ToolResult] (permission or validation) out of a helper. */+ private class ResultCarrier(val result: ToolResult) : Exception(result.message)++ private fun fail(message: String): Result<File> = Result.failure(ResultCarrier(ToolResult.error(message)))++ /** Unwraps a [ResultCarrier] failure back into the [ToolResult] the caller returns. */+ private inline fun Result<File>.unwrap(onFailure: (ToolResult) -> Nothing): File =+ fold(+ onSuccess = { it },+ onFailure = { e -> onFailure((e as? ResultCarrier)?.result ?: ToolResult.error(e.message.orEmpty())) }+ )+}diff --git a/app/src/main/java/com/gotcha/tools/MediaExport.kt b/app/src/main/java/com/gotcha/tools/MediaExport.ktnew file mode 100644index 0000000..4fdb8d2--- /dev/null+++ b/app/src/main/java/com/gotcha/tools/MediaExport.kt@@ -0,0 +1,201 @@+package com.gotcha.tools++import android.content.Context+import android.net.Uri+import androidx.annotation.OptIn+import androidx.media3.common.MediaItem+import androidx.media3.common.util.UnstableApi+import androidx.media3.transformer.Composition+import androidx.media3.transformer.EditedMediaItem+import androidx.media3.transformer.ExportException+import androidx.media3.transformer.ExportResult+import androidx.media3.transformer.Transformer+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.suspendCancellableCoroutine+import kotlinx.coroutines.withContext+import kotlinx.coroutines.withTimeoutOrNull+import java.io.File+import kotlin.coroutines.resume++/**+ * Runs one Media3 [Transformer] export and suspends until it finishes.+ *+ * Bridging Transformer into a `suspend` function is most of the work here.+ * Transformer is callback-driven and must be built, started and cancelled on a+ * thread with a [android.os.Looper], while [ToolExecutor] dispatches every tool+ * on `Dispatchers.IO`, which has none. So the export is hopped onto the main+ * dispatcher and its listener resumed through [suspendCancellableCoroutine].+ *+ * The whole call is bounded by [TIMEOUT_MS]. A transmux finishes in seconds, but+ * a re-encode of a long 4K video does not, and an export that never calls back+ * would otherwise wedge the agent loop with no way out.+ */+@OptIn(UnstableApi::class)+class MediaExport(private val context: Context) {++ companion object {+ /**+ * Ceiling on a single export. Generous enough for a real re-encode on a+ * slow device, short enough that a wedged codec surfaces as an error the+ * model can report rather than a hang the user has to force-quit.+ */+ const val TIMEOUT_MS = 10L * 60 * 1000+ }++ /**+ * Outcome of an export, in the two shapes the caller cares about: whether it+ * failed, and whether the codecs ran.+ *+ * @param videoEncoder name of the video encoder used, or null when the video+ * track was stream-copied (or absent). Same for [audioEncoder].+ */+ data class Outcome(+ val error: ToolResult?,+ val videoEncoder: String?,+ val audioEncoder: String?+ ) {+ fun failure(): ToolResult? = error++ /** True when neither track went through a codec — a pure container rewrite. */+ val wasTransmuxed: Boolean get() = videoEncoder == null && audioEncoder == null++ /**+ * Appended to a success message. Whether the edit was lossless is the thing+ * a user most often wants to know afterwards and can never tell by looking,+ * so it is stated in the result rather than left implicit.+ */+ fun qualityNote(): String = if (wasTransmuxed) {+ " The streams were copied rather than re-encoded, so there is no quality loss."+ } else {+ val used = listOfNotNull(videoEncoder, audioEncoder).joinToString(", ")+ " NOTE: this was re-encoded ($used) rather than copied, so it lost a little quality. " ++ "Re-encoding the same file repeatedly compounds that."+ }+ }++ /**+ * Exports [input] to [output], optionally clipped to [clip] and with either+ * track dropped. With no clip and no removals this is a plain container+ * rewrite, which Transformer still performs as a stream copy.+ */+ suspend fun run(+ input: File,+ output: File,+ clip: LongRange? = null,+ removeAudio: Boolean = false,+ removeVideo: Boolean = false+ ): Outcome {+ val outcome = withTimeoutOrNull(TIMEOUT_MS) {+ withContext(Dispatchers.Main) {+ export(input, output, clip, removeAudio, removeVideo)+ }+ }+ 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+ }++ @Suppress("LongParameterList")+ private suspend fun export(+ input: File,+ output: File,+ clip: LongRange?,+ removeAudio: Boolean,+ removeVideo: Boolean+ ): Outcome = suspendCancellableCoroutine { continuation ->+ val item = MediaItem.Builder()+ .setUri(Uri.fromFile(input))+ .apply {+ clip?.let {+ setClippingConfiguration(+ MediaItem.ClippingConfiguration.Builder()+ .setStartPositionMs(it.first)+ .setEndPositionMs(it.last)+ .build()+ )+ }+ }+ .build()++ val edited = EditedMediaItem.Builder(item)+ .setRemoveAudio(removeAudio)+ .setRemoveVideo(removeVideo)+ .build()++ val transformer = Transformer.Builder(context)+ .addListener(object : Transformer.Listener {+ override fun onCompleted(composition: Composition, result: ExportResult) {+ if (continuation.isActive) {+ continuation.resume(+ Outcome(+ error = null,+ videoEncoder = result.videoEncoderName,+ audioEncoder = result.audioEncoderName+ )+ )+ }+ }++ override fun onError(+ composition: Composition,+ result: ExportResult,+ exception: ExportException+ ) {+ runCatching { if (output.exists()) output.delete() }+ if (continuation.isActive) {+ continuation.resume(+ Outcome(+ error = ToolResult.error(describeExportError(exception, input)),+ videoEncoder = null,+ audioEncoder = null+ )+ )+ }+ }+ })+ .build()++ continuation.invokeOnCancellation {+ // cancel() must run on the thread that built the Transformer.+ runCatching { transformer.cancel() }+ }+ transformer.start(edited, output.absolutePath)+ }++ /**+ * Turns an [ExportException] into something a model can act on. The raw+ * messages are codec-level ("Decoder init failed: OMX.…") and read as an app+ * bug rather than as a property of the file.+ */+ private fun describeExportError(exception: ExportException, input: File): String {+ val message = exception.message.orEmpty()+ val cause = exception.cause?.message.orEmpty()+ val combined = "$message $cause"+ return when {+ combined.contains("DRM", ignoreCase = true) || combined.contains("crypto", ignoreCase = true) ->+ "'${input.name}' is DRM-protected, so it cannot be edited. Tell the user plainly; there is no " ++ "retry that will work."+ exception.errorCode == ExportException.ERROR_CODE_IO_FILE_NOT_FOUND ->+ "'${input.name}' could not be read while exporting — it may have been moved or deleted mid-edit."+ exception.errorCode == ExportException.ERROR_CODE_IO_NO_PERMISSION ->+ "Permission was refused while reading or writing during the export of '${input.name}'."+ combined.contains("Decoder init", ignoreCase = true) ||+ combined.contains("Encoder init", ignoreCase = true) ->+ "This device's codecs could not handle '${input.name}' (${combined.trim()}). The format is " ++ "readable but not editable here; ffmpeg via run_termux_command is the fallback."+ else -> "The export failed: ${combined.trim().ifEmpty { "no detail reported" }}."+ }+ }+}diff --git a/app/src/main/java/com/gotcha/tools/MediaProbe.kt b/app/src/main/java/com/gotcha/tools/MediaProbe.ktnew file mode 100644index 0000000..122bc49--- /dev/null+++ b/app/src/main/java/com/gotcha/tools/MediaProbe.kt@@ -0,0 +1,167 @@+package com.gotcha.tools++import android.media.MediaExtractor+import android.media.MediaFormat+import android.media.MediaMetadataRetriever+import java.io.File+import java.util.Locale++/**+ * What a media file actually contains, read without decoding a single frame.+ *+ * Every [MediaEditTool] operation needs this before it can decide anything:+ * `trim` needs the duration to clamp against, `remove_audio` needs to know an+ * audio track exists, and the model needs the whole picture to choose an+ * operation at all. Reading it is cheap — [MediaExtractor] parses the container+ * header and [MediaMetadataRetriever] the metadata atoms, neither of which+ * starts a codec.+ *+ * [hasVideo] and [hasAudio] are the load-bearing fields. An .mp4 with no audio+ * track and an .m4a are both legitimate inputs, and the operations that make no+ * sense for them have to be refused with a real explanation rather than writing+ * an empty file.+ */+data class MediaProbe(+ val durationMs: Long,+ val hasVideo: Boolean,+ val hasAudio: Boolean,+ val videoMime: String?,+ val audioMime: String?,+ val width: Int,+ val height: Int,+ val rotationDegrees: Int,+ val frameRate: Int,+ val sampleRateHz: Int,+ val channelCount: Int,+ val bitrateBps: Long+) {++ /** True when the container holds audio and nothing else — an .m4a, .mp3, .wav. */+ val isAudioOnly: Boolean get() = hasAudio && !hasVideo++ /**+ * Display dimensions, i.e. after the container's rotation metadata is applied.+ * A portrait phone video is stored as 1920x1080 with rotation=90, and reporting+ * the stored numbers makes the model think it is landscape.+ */+ val displayWidth: Int get() = if (rotationDegrees % 180 == 90) height else width+ val displayHeight: Int get() = if (rotationDegrees % 180 == 90) width else height++ /** One-line summary for a tool result, written for the model to reason over. */+ @Suppress("ComplexMethod")+ fun describe(): String {+ val parts = mutableListOf<String>()+ parts += if (durationMs > 0) MediaTimeSpec.format(durationMs) else "unknown duration"+ if (hasVideo) {+ val video = buildString {+ append("video ${displayWidth}x$displayHeight")+ if (frameRate > 0) append(" @ ${frameRate}fps")+ videoMime?.let { append(" (${it.removePrefix("video/")})") }+ if (rotationDegrees != 0) append(", rotated $rotationDegrees°")+ }+ parts += video+ } else {+ parts += "no video track"+ }+ if (hasAudio) {+ val audio = buildString {+ append("audio")+ if (channelCount > 0) append(" ${channelDescription()}")+ if (sampleRateHz > 0) append(" ${"%.1f".format(Locale.ROOT, sampleRateHz / 1000.0)}kHz")+ audioMime?.let { append(" (${it.removePrefix("audio/")})") }+ }+ parts += audio+ } else {+ parts += "no audio track"+ }+ if (bitrateBps > 0) parts += "${bitrateBps / 1000} kbps"+ return parts.joinToString(", ")+ }++ private fun channelDescription(): String = when (channelCount) {+ 1 -> "mono"+ 2 -> "stereo"+ else -> "$channelCount-channel"+ }++ companion object {++ /**+ * Reads [file]'s container header. Throws whatever the platform throws for+ * an unreadable file — [MediaEditTool] translates those into model-facing+ * messages, since the raw exceptions are unhelpful ("Failed to instantiate+ * extractor" for a DRM file, for instance).+ */+ fun of(file: File): MediaProbe {+ val extractor = MediaExtractor()+ var hasVideo = false+ var hasAudio = false+ var videoMime: String? = null+ var audioMime: String? = null+ var width = 0+ var height = 0+ var frameRate = 0+ var sampleRate = 0+ var channels = 0+ try {+ extractor.setDataSource(file.absolutePath)+ for (i in 0 until extractor.trackCount) {+ val format = extractor.getTrackFormat(i)+ val mime = format.getString(MediaFormat.KEY_MIME).orEmpty()+ when {+ mime.startsWith("video/") && !hasVideo -> {+ hasVideo = true+ videoMime = mime+ width = format.intOrZero(MediaFormat.KEY_WIDTH)+ height = format.intOrZero(MediaFormat.KEY_HEIGHT)+ frameRate = format.intOrZero(MediaFormat.KEY_FRAME_RATE)+ }+ mime.startsWith("audio/") && !hasAudio -> {+ hasAudio = true+ audioMime = mime+ sampleRate = format.intOrZero(MediaFormat.KEY_SAMPLE_RATE)+ channels = format.intOrZero(MediaFormat.KEY_CHANNEL_COUNT)+ }+ }+ }+ } finally {+ extractor.release()+ }++ val retriever = MediaMetadataRetriever()+ var durationMs = 0L+ var rotation = 0+ var bitrate = 0L+ try {+ retriever.setDataSource(file.absolutePath)+ durationMs = retriever.longOrZero(MediaMetadataRetriever.METADATA_KEY_DURATION)+ rotation = retriever.longOrZero(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION).toInt()+ bitrate = retriever.longOrZero(MediaMetadataRetriever.METADATA_KEY_BITRATE)+ } finally {+ runCatching { retriever.release() }+ }++ return MediaProbe(+ durationMs = durationMs,+ hasVideo = hasVideo,+ hasAudio = hasAudio,+ videoMime = videoMime,+ audioMime = audioMime,+ width = width,+ height = height,+ rotationDegrees = Math.floorMod(rotation, 360),+ frameRate = frameRate,+ sampleRateHz = sampleRate,+ channelCount = channels,+ bitrateBps = bitrate+ )+ }++ /** [MediaFormat] throws rather than defaulting when a key is absent. */+ private fun MediaFormat.intOrZero(key: String): Int =+ if (containsKey(key)) runCatching { getInteger(key) }.getOrDefault(0) else 0++ private fun MediaMetadataRetriever.longOrZero(key: Int): Long =+ extractMetadata(key)?.toLongOrNull() ?: 0L+ }+}