I want to compress videos for sharing in my Android app. These are my preferred settings:
Resolution: 1280x720
Container: MP4
Video codec: H.264
Video bitrate: 3 Mbit/s
Video FPS: 30
Audio codec: AAC
Audio sampling rate: 44100
Audio bitrate: 128 kbit/s
MoveMoov atom
to the start to enable streaming (optional)
I do not want to use FFmpeg as it uses software encoders and is very slow. I am getting about 0.7x encoding speed when converting an H.265, 1080p, 120 fps, 40 Mbit/s video to the above settings. Also I want to avoid the hassle of managing an NDK library.
So I eventually settled on Jetpack Media3 Transformer for my use case. And I have this code working perfectly:
val transformationRequest = TransformationRequest.Builder()
.setVideoMimeType(MimeTypes.VIDEO_H264)
.setAudioMimeType(MimeTypes.AUDIO_AAC)
.setResolution(1280)
.build()
val inputMediaItem = MediaItem.fromUri(uri)
val outputFile = MediaUtils.createTempFile(c,MediaType.VIDEO)
// Create a Transformer
val transformer = Transformer.Builder(c)
.setTransformationRequest(transformationRequest) // Pass in TransformationRequest
.addListener(object: Transformer.Listener {
override fun onTransformationCompleted(inputMediaItem: MediaItem, transformationResult: TransformationResult) {
super.onTransformationCompleted(inputMediaItem, transformationResult)
Log.d("ENCODE", "Encoding Complete")
Log.d("ENCODE", "Output Size: ${MediaUtils.getFileSize(outputFile)}")
}
}) // transformerListener is an implementation of Transformer.Listener
.build()
withContext(Dispatchers.Main) {
// Start the transformation
transformer.startTransformation(inputMediaItem, outputFile.absolutePath)
}
This encode completes at 4-5x speed. But I don’t see a way to set anything except the codecs and resolution. The Transformer Documentation does say this:
video encoding works with default settings, but you can also pass custom video encoder settings or replace the encoder factory to get complete control over how encoders are used
But I cannot find any documentation on how to set the video fps and video/audio bitrate.