JMR-devandClaude Opus 5 dbfc463c6d Delete the half-written destination instead of leaving it under the user's name
publish() streamed the staged file into the SAF destination with copyTo and had no
answer for a copy that failed partway. The destination volume filling up is the obvious
way in; a provider giving out mid-write is the other. Either way the bytes it had
managed stayed at the name the user picked, while the UI said "Could not save the file".
The user was left holding a truncated file they had just been told was never written,
and nothing in the app would ever tidy it up -- staging cleanup reaches
<cacheDir>/conversions and nowhere else, by design.

So a failed copy now deletes the document. The interesting part is not the delete, it is
what stops it, because removing a file the user already had would be a far worse defect
than the one being fixed.

  Only a document URI. DocumentsContract.deleteDocument is the only delete this code has
  any right to attempt and it is defined on document URIs, so isDocumentUri() gates it.
  That is not a formality: it asks the package manager whether anything answers
  ACTION_DOCUMENTS_PROVIDER for the authority, so a file:// path, a MediaStore item or a
  content URI from an ordinary provider all fall out here untouched.

  Only a destination that was empty when we started. The size is read BEFORE the stream
  is opened -- opening for write truncates, so afterwards the question can no longer be
  asked -- and the delete runs only when the answer was positively zero. Every
  destination that reaches publish() today comes from the SAF CreateDocument contract, so
  in practice it is a document this app created seconds earlier; but publish() cannot
  verify that from a Uri, and a provider that hands back an EXISTING document for a name
  the user re-picked would otherwise have its file deleted rather than merely truncated.
  Truncated is bad. Gone is worse, and it is the user's file either way.

  That guard fails towards doing nothing. A provider that does not report _size, a query
  that returns no row, a resolver call that throws -- all of them land in "not known to
  be empty", so the fix is conservative rather than universal: it will not clean up
  behind such a provider, and it will not delete anything of theirs either. The defect is
  closed for providers that answer a size query; ExternalStorageProvider backs its
  documents with real files, so a freshly created one reports 0, but that is reasoning
  about it rather than a run against it. Stated here rather than implied, because
  "fixed" would overclaim what was verified.

  The original failure is what the caller sees. Cleanup runs in its own runCatching and a
  throw from it is attached to the original exception as a suppressed one. deleteDocument
  reports failure two different ways -- false, or a rethrown RuntimeException -- and
  neither is worth failing the save over, because the save has already failed.
  ConversionViewModel.save() reports e.message, and "could not delete the half-written
  file" is not what to tell someone whose disk just filled up.

Two smaller decisions in the control flow. The whole `use` is guarded, not just copyTo:
a close() that throws while flushing IS the disk-full case and it arrives after copyTo
has returned successfully, so guarding only the copy would miss exactly the failure this
commit is about. The cost is that a file whose every byte reached the provider before a
failing flush is deleted too, which is the right way round -- a flush that failed means
the bytes are not durably there. And openOutputStream's own failure is deliberately
OUTSIDE the guard: nothing has been written at that point, so there is nothing of ours to
remove.

Nothing else in the class moves. hasSpaceFor, discardStaged and sweepStaging are
untouched, and so is save(): the staged file is still deliberately kept on a failed save,
for the reason its own comment gives -- it may be the only copy of an hour of
transcoding, and now the destination genuinely does not have it either.

Seven tests, JVM, Robolectric. The failure has to be injected, which is what shapes them:
Robolectric's ShadowContentResolver consults its registered-stream map before it reaches
any provider, so a test can hand out a stream that writes 512 bytes to a real file and
then throws "No space left on device" while a fake provider answers the size query and
the delete against that same file. The provider is registered twice under two authorities
and two component names, once with the ACTION_DOCUMENTS_PROVIDER intent filter and once
without, which is the only way to have a content URI that is not a document URI. The
delete is observed by the wire names DocumentsContract.deleteDocument actually sends --
"android:deleteDocument" and the "uri" extra -- because both constants are hidden from
the public SDK.

  fails partway leaves nothing        RED before the fix: expected the delete, got []
  close that fails while flushing     RED before: the file was still there
  cleanup that fails                  RED before: suppressed was []
  already held bytes is not deleted   green before the fix -- see below
  not a document is left alone        green before the fix -- see below
  cannot be opened at all             green before, and must stay so
  succeeds, every byte, no delete     green before, and must stay so

The last four are green against the unfixed code for a reason worth writing down: the old
publish() never deleted anything, so every guard passes trivially. They pin the guards
rather than the defect, and pinning is only worth something if the pin is real, so both
were reverted on their own:

  - dropping `if (destinationWasEmpty)` fails "a destination that already held bytes is
    not deleted" with "a document this app did not create must survive"
  - dropping the isDocumentUri() check fails "a destination that is not a document is
    left alone" with "deleteDocument has no business on a URI that is not a document
    expected:<[]> but was:<[content://...test.plain/document/holiday_plain.mp4]>"

Both were restored. 193 unit tests green.

UnopenableUriTest's unwritable-destination case (an authority with no provider behind it)
is unchanged and keeps passing by two independent routes: the size query on a dead
authority yields "not known to be empty", and the failure itself comes out of
openOutputStream, which sits outside the guard. It is an instrumented test and was
compile-verified here, not executed -- instrumented tests do not run on this host
(CLAUDE.md). Its JVM twin is in the list above.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 19:45:17 -05:00
2026-08-19 17:29:15 -05:00

LibreMediaConverter

A free and open-source media converter for Android — batch video transcoding and compression, audio extraction and conversion, GIF and frame export, and file merging.

Android 13+ (API 33). Built with Jetpack Compose and Material 3.

Status: working, unreleased. Both conversion engines, the router, the background job queue and the join flow are implemented and building. The FFmpeg format tests have been written but not yet executed on a device.

Licensing at a glance

  • Source code: MIT
  • Distributed APK: GPL-3.0 — because it bundles FFmpeg built with x264/x265

That split is deliberate, not an oversight. See LICENSES/README.md for the reasoning and the corresponding-source obligations.

Architecture

Two conversion engines behind an explicit router, because neither one covers the job alone.

AndroidX Media3 Transformer — the hardware path

Handles the common cases: H.264/HEVC, resolution and frame-rate changes, rotation, overlays, and audio to AAC. Fully hardware accelerated end to end — MediaCodec decodes to a GL surface and MediaCodec re-encodes, so frames never round-trip through the CPU. Roughly 7–8× realtime on 720p.

It writes MP4 and nothing else. media3-muxer ships WebM, Ogg, WAV and AAC muxers too, but none can be driven by Transformer — they throw from addMetadataEntry, which the muxer wrapper calls for every metadata entry a real recording carries. It reads far more than it writes, Matroska included, which is what makes MKV → MP4 a hardware remux.

FFmpeg — the long tail

Everything Media3 structurally cannot do:

  • Containers outside MP4/WebM/Ogg/WAV/AAC — MKV, MOV, AVI, FLV, MPEG-TS, WMV/ASF
  • MP3 output — Android has no MP3 encoder at any version; this is a platform gap
  • GIF and image sequences
  • Input codecs with no platform decoder on the device
  • CRF and 2-pass rate control, for the quality tier
  • Codecs Media3's muxers decline even on a stream copy — its MP4 muxer carries AAC, Opus, Vorbis and PCM, but neither MP3 nor FLAC

Quality tiers

The router is surfaced to users as a quality choice rather than hidden:

Tier Engine Rate control Trade-off
Fast (default) Media3 / MediaCodec bitrate-targeted ~7–8× realtime, low battery cost
Best quality FFmpeg + x264/x265 CRF or 2-pass ~realtime or slower, better quality per byte

A note on "GPU acceleration"

Android has no GPU video codec path. There are three distinct tiers, and conflating them causes a lot of confusion:

  1. Fixed-function video codec silicon — reached through MediaCodec. This is what "hardware accelerated" means for encode and decode. It is not the GPU.
  2. GPU shader cores — genuinely used, but only for filters, scaling, and color effects on already-decoded frames, via OpenGL ES. Never for entropy coding.
  3. CPU — x264, x265, and software decoders.

FFmpeg's -hwaccel is meaningful on Android only as mediacodec, and even then it targets direct-to-Surface playback rather than file-to-file transcoding. Vulkan Video exists in FFmpeg 8.0+ but no shipping Android GPU driver exposes it — no VK_KHR_video_* extension appears in any Android Vulkan Profile tier.

So this app is hardware accelerated via MediaCodec, and GPU accelerated for effects via GL shaders. Both are real; neither is "the GPU decoding video."

Remuxing

Changing the container without touching the streams. Copying an H.264 track from MKV into MP4 moves the same samples into a different wrapper: it finishes in seconds instead of minutes, costs no quality, and needs no encoder — which is why it stays on the hardware path even on a device that cannot encode the codec in question.

Copy is a codec choice like any other, so it can be mixed: copy the video and re-encode only the audio, or the reverse. Picking a codec the source already uses is upgraded to a copy automatically when the container is changing — if container and codec both already match, the only reason to run the job is to re-encode it, so it does.

A copy is never attempted on a stream whose codec could not be identified. A needless re-encode costs time; a wrong stream copy costs a file that will not play.

Features

Formats
Video out MP4, MOV, MKV, WebM, MPEG-TS, AVI, FLV, WMV/ASF
Video codecs H.264, H.265, VP9, or copy the source stream
Audio out MP3, AAC/M4A, FLAC, Opus, WAV, MKA
Audio codecs AAC, Opus, MP3, FLAC, PCM, or copy the source stream
Images GIF, PNG frame sequences
Other Remux without re-encoding; join several files into one

Presets cover the common combinations in one tap. The Advanced picker exposes the full container × codec matrix — including combinations that cannot work, which it explains and offers alternatives for rather than hiding.

Conversions run as durable background work, so they survive leaving the app and are restored after a restart.

Building

Requires JDK 17+ (AGP 9 will not run on older) and the Android SDK with API 37.

FFmpeg is committed as a prebuilt archive under bin/, so a clone builds without a cross-compile. That is deliberate: rebuilding it per CI run made test results ambiguous, because a red build could mean broken code or a build that hiccuped. See bin/README.md for its provenance and how to regenerate it.

./gradlew :app:assembleDebug          # debug APK
./gradlew :app:testDebugUnitTest      # JVM tests
./gradlew :app:connectedDebugAndroidTest   # device tests, needs a running device
./gradlew :app:assembleRelease        # R8-minified release

See tools/ffmpeg/README.md for why the build is containerised and which flags matter. That recipe remains the authority — the committed archive is its output, and is also what satisfies the GPL corresponding-source obligation.

Testing

Unit tests cover the parts that decide correctness without needing hardware: the routing matrix, the container × codec capability matrix, the FFmpeg argument builder, and both stream-copy-versus-re-encode planners. They run against fabricated device profiles, so branches like "this device cannot encode HEVC" are reachable regardless of what the test machine is.

Instrumented tests cover the parts that only a device can prove: real hardware transcoding, the foreground service type, and each FFmpeg output format asserted against the produced file rather than the exit code. The remux tests additionally assert which engine ran — a stream copy produces an identical file either way, so an output-only assertion cannot tell a hardware transmux from FFmpeg's -c copy.

Privacy

The app has no INTERNET permission, so it cannot open a network connection at all. Nothing is uploaded, and there is no analytics or advertising. See PRIVACY.md, which also explains the permissions WorkManager adds automatically.

Contributing

Contributions are welcome. Note that contributions to the source are under MIT, while the distributed binary remains GPL-3.0 for the reasons described in LICENSES/README.md.

S
Description
On-device FOSS media converter for mobile. Android first, iOS aspirational. Android flavor uses Media3 and FFMPEG.
Readme MIT
70 MiB
Languages
Kotlin 91.1%
Shell 7.4%
Java 1.4%
Dockerfile 0.1%